How to read and write text files in Java? The old way was to use java.io package, since Java SE 7 there's new java.nio package where are classes like Files, Paths and Path:
public static void main(String[] args) throws IOException { // write to text file ArrayListlines = new ArrayList (); lines.add("hello world"); lines.add("hello world 2nd line"); Path pathToFile = Paths.get("file.txt"); Files.write(pathToFile, lines); // read from text file List lines2 = Files.readAllLines(pathToFile); for (String line : lines2) { System.out.println(line); } }
How to use UTF-8:
Files.write(pathToFile, lines, StandardCharsets.UTF_8); Files.readAllLines(pathToFile, StandardCharsets.UTF_8);
How to use custom charset:
Files.write(pathToFile, lines, Charset.forName("iso-8859-2")); Files.readAllLines(pathToFile, Charset.forName("iso-8859-2"));
How to append:
Files.write(pathToFile, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);