Sunday, 16 November 2014

How to write to and read from text files in Java/Android

There are many ways to read and write files in Java and the size and type of data you're working with usually dictate the best method to do so.

For working with text files that are small enough, I find that the classes FileReader and FileWriter provide the most cost effective implementations.

The helper methods below are ready for use. They rely on the system's default Charset so be careful if you're passing around files across different systems and encodings. The code works on any Java platform including Android.

public static void saveToTextFile(String fileName, String contents) throws IOException{
 Writer writer = new BufferedWriter(new FileWriter(fileName));
 try{
  writer.write(contents);
 }finally{
  writer.close();
 }
}

public static String readTextFile(String fileName) throws IOException{
 Reader reader = new BufferedReader(new FileReader(fileName));
 try{
  char[] buffer = new char[1024*8];
  StringBuilder resultBuilder = new StringBuilder();
  int br;   
  while((br = reader.read(buffer))>0){
   resultBuilder.append(buffer, 0, br);
  }
  return resultBuilder.toString();
 }finally{
  reader.close();
 }
}


An usage example on Android would be
// 'this' here is the activity context
String fileName = this.getFilesDir().getAbsolutePath()+"/test.txt";
String contents = "Hello, World of Android";
try {
 saveToTextFile(fileName, contents);
 //do something...
 String contentsRead = readTextFile(fileName);
 Log.d("MYAPP", "I wrote '"+contents+"' and I read '"+contentsRead+"'");
} catch (IOException e) {   
 Log.e("MYAPP", e.getMessage(),e);
}

No comments:

Post a Comment