Skip to content

Instantly share code, notes, and snippets.

@jasonqu
Last active August 29, 2015 14:00
Show Gist options
  • Save jasonqu/11130969 to your computer and use it in GitHub Desktop.
Save jasonqu/11130969 to your computer and use it in GitHub Desktop.
// http://www.javapractices.com/topic/TopicAction.do?Id=42
// In JDK7
List<String> lines = Files.readAllLines(Paths.get("a.txt"), Charset.forName("utf8"));
Files.write(Paths.get("b.txt"), lines, Charset.forName("utf8"));
// for big file
Path path = Paths.get(aFileName);
try (BufferedReader reader = Files.newBufferedReader(path, ENCODING)){
String line = null;
while ((line = reader.readLine()) != null) {
//process each line in some way
}
}
try (BufferedWriter writer = Files.newBufferedWriter(path, ENCODING)){
for(String line : aLines){
writer.write(line);
writer.newLine();
}
}
// Or use PrintWriter
PrintWriter out = new PrintWriter("filename.txt");
out.println(text);
// In Java 8
// http://stackoverflow.com/questions/4716503/best-way-to-read-a-text-file
Files.lines(..).forEach(...)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment