logo

How to read and write text files since Java SE 7

How to use Java SE 7 java.nio package with classes like Files, Paths and Path to read and write text files in Java. Plus how to use UTF-8 and other charset (encoding) and how to append (not overwrite) text file.

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
	ArrayList lines = 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);

comments powered by Disqus

rss

Free online Java web application examples

Want to develop whole web applications which use database, security and more? See my github account, where are lot's of example projects:
github

Search