Jakub Provazník
Jakub Provazník

Reputation: 29

Loading and processing a file using Stream

I have a task to do. Load a text file with multiple lines, print the text on the console, convert text to uppercase, and save it to another text file.

public static void main(String[] args) throws IOException {
    String fileName = "src/PISMENA.txt";
    Stream<String> stream = Files.lines(Paths.get(fileName));
    stream.map(String::toUpperCase).forEach(System.out::println);
}

I want to do it as simple as possible so I tried to used Stream form java 8. I do not know how to continue with that. One option is to convert Stream to List and work with that, but it removes lines and whole text is on one line. What are my options how to do that?

Upvotes: 2

Views: 1600

Answers (2)

Thomas Fritsch
Thomas Fritsch

Reputation: 10147

Stream<String> stream = Files.lines(Paths.get(fileName));
PrintStream output = new PrintStream(new FileOutputStream("output.txt"));
stream.map(String::toUpperCase).forEach(output::println);

// and don't forget to close
stream.close();
output.close();

Upvotes: 0

Beri
Beri

Reputation: 11620

Adding to file will leave to you:)

Files.lines(Paths.get(fileName))
   .peek(System.out::println)
   .map(String::toUpperCase)
   .forEach(line-> //*add to file*//)

Upvotes: 4

Related Questions