Text File Read and Write Method Write File

  • Slides: 7
Download presentation
Text File Read and Write Method

Text File Read and Write Method

Write File String fcontent; String fname; String fpath = “/sdcard/”+fname+“. txt”; File file =

Write File String fcontent; String fname; String fpath = “/sdcard/”+fname+“. txt”; File file = new File(fpath); // If file does not exists, then create it if (!file. exists()) { file. create. New. File(); } File. Writer fw = new File. Writer(file. get. Absolute. File()); Buffered. Writer bw = new Buffered. Writer(fw); bw. write(fcontent); bw. close();

Read File – Line method String fname; Buffered. Reader br = null; String response

Read File – Line method String fname; Buffered. Reader br = null; String response = null; try { String. Buffer output = new String. Buffer(); String fpath = "/sdcard/"+fname+". txt"; br = new Buffered. Reader(new File. Reader(fpath)); String line = ""; while ((line = br. read. Line()) != null) { output. append(line +“n”); } response = output. to. String();

Read File – Buffer method File. Input. Stream file. In=open. File. Input("mytextfile. txt"); Input.

Read File – Buffer method File. Input. Stream file. In=open. File. Input("mytextfile. txt"); Input. Stream. Reader Input. Read= new Input. Stream. Reader(file. In); char[] input. Buffer= new char[READ_BLOCK_SIZE]; String s=""; int char. Read; while ((char. Read=Input. Read. read(input. Buffer))>0) { // char to string conversion String readstring=String. copy. Value. Of(input. Buffer, 0, char. Read); s +=readstring; } Input. Read. close();

Stream Method File output. File=new File(FILE_PATH+“/”+FILE_NAME); File. Output. Stream output. Stream; try { output.

Stream Method File output. File=new File(FILE_PATH+“/”+FILE_NAME); File. Output. Stream output. Stream; try { output. Stream = new File. Output. Stream(output. File); output. Stream. write(write. Txt. get. Text(). to. String(). get. Byt es()); output. Stream. close(); } catch (File. Not. Found. Exception e) { e. print. Stack. Trace(); } catch (IOException e) { e. print. Stack. Trace(); }

Stream Method File input. File=new File(FILE_PATH+“/”+FILE_NAME); int length=(int)input. File. length(); File. Input. Stream input.

Stream Method File input. File=new File(FILE_PATH+“/”+FILE_NAME); int length=(int)input. File. length(); File. Input. Stream input. Stream; try { input. Stream = new File. Input. Stream(input. File); byte[] buffer=new byte[length]; input. Stream. read(buffer); input. Stream. close(); String string=“”;

 for(int i=0; i<buffer. length; i++) { char c=(char) buffer[i]; string+=c; } read. Txt.

for(int i=0; i<buffer. length; i++) { char c=(char) buffer[i]; string+=c; } read. Txt. set. Text(string); } catch (File. Not. Found. Exception e) { e. print. Stack. Trace(); } catch (IOException e) { e. print. Stack. Trace(); }