File I/O operations

Several short snippets for File I/O in generic Java.

Read a file into a String

FileInputStream fis = context.openFileInput("hello.txt", Context.MODE_PRIVATE);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
    sb.append(line);
}

Write a String to a file

BufferedWriter writer = new BufferedWriter(new FileWriter("hello.txt"));
// Write to the file:
writer.write(str);
// Or append instead:
writer.append(str);
writer.close();

Write bytes to a file

FileOutputStream outputStream = new FileOutputStream("hello.txt");
byte[] bytes = ...
outputStream.write(bytes);
outputStream.close();