Quantcast
Viewing all articles
Browse latest Browse all 36

Answer by Andrei N for How do I create a Java string from the contents of a file?

If you need a string processing (parallel processing) Java 8 has the great Stream API.

String result = Files.lines(Paths.get("file.txt"))                    .parallel() // for parallel processing                     .map(String::trim) // to change line                       .filter(line -> line.length() > 2) // to filter some lines by a predicate                                            .collect(Collectors.joining()); // to join lines

More examples are available in JDK samples sample/lambda/BulkDataOperations that can be downloaded from Oracle Java SE 8 download page

Another one liner example

String out = String.join("\n", Files.readAllLines(Paths.get("file.txt")));

Viewing all articles
Browse latest Browse all 36

Trending Articles