Presentation is loading. Please wait.

Presentation is loading. Please wait.

Text File Read and Write Method

Similar presentations


Presentation on theme: "Text File Read and Write Method"— Presentation transcript:

1 Text File Read and Write Method

2 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.createNewFile();  } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(fcontent); bw.close();

3 Read File – Line method String fname; BufferedReader br = null;
 String response = null;  try {         StringBuffer output = new StringBuffer();         String fpath = "/sdcard/"+fname+".txt";         br = new BufferedReader(new FileReader(fpath));         String line = "";         while ((line = br.readLine()) != null) {           output.append(line +“\n”);  }  response = output.toString();

4 Read File – Buffer method
FileInputStream fileIn=openFileInput("mytextfile.txt"); InputStreamReader InputRead= new InputStreamReader(fileIn); char[] inputBuffer= new char[READ_BLOCK_SIZE]; String s=""; int charRead; while ((charRead=InputRead.read(inputBuffer))>0) { // char to string conversion String readstring=String.copyValueOf(inputBuffer,0,charRead); s +=readstring; } InputRead.close(); Toast.makeText(getBaseContext(), s ,Toast.LENGTH_SHORT).show();

5 Stream Method File outputFile=new File(FILE_PATH+“/”+FILE_NAME);
FileOutputStream outputStream; try { outputStream = new FileOutputStream(outputFile); outputStream.write(writeTxt.getText().toString().getBytes()); outputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { }

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

7 for(int i=0; i<buffer.length; i++) {
char c=(char) buffer[i]; string+=c; } readTxt.setText(string); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) {


Download ppt "Text File Read and Write Method"

Similar presentations


Ads by Google