September 16, 2016

How To Read from a Text File in Java

BufferedReader reader = null;
try {
    reader = new BufferedReader(new InputStreamReader(new FileInputStream("filename.txt"), "UTF-8"));
    String string = reader.readLine();
} finally {
    if (reader != null) {
        reader.close();
    }
}

How To Write to a Text File in Java

Writer writer = null;
try {
    writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("filename.txt"), "UTF-8"));
    writer.write(string);
} finally {
    if (writer != null) {
        writer.close();
    }
}