-2

I'm using this code, it runs well but i need to add "\n" to each line

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    filename = "Reverse.txt";
    file = new File(filename);
    try (final Stream<String> lines = Files.lines(Paths.get(filename))) {
        lines.collect(Collectors.toCollection(LinkedList::new))
        .descendingIterator()
        .forEachRemaining(jTextArea1::append); // <<<<<<< need "\n"
    }   
    catch (IOException ex) {                
        Logger.getLogger(TextAreaReverseReadFrame.class.getName()).log(Level.SEVERE, null, ex);
    }                
} 

2 Answers 2

1

You can transform each line at source, meaning adding a map instruction just before the collect one:

lines.map(element -> element + '\n').collect(Collectors.toCollection(LinkedList::new)).descendingIterator()
                .forEachRemaining(testBuilder::append);
1
  • thanks Bsquare, at the beginning I did not understand your solution, but it works well
    – patel
    Nov 9, 2018 at 16:34
0

Simply try to change

.forEachRemaining(jTextArea1::append);

to:

.forEachRemaining(singleLine -> jTextArea1.append(singleLine  + "\n"));
3
  • I think it would be more stream-esque if you add \n to the text with a separate .map call
    – Tim
    Nov 9, 2018 at 8:41
  • I don't understand what that has to do with my comment
    – Tim
    Nov 9, 2018 at 8:48
  • thanks Pijotrek, your code solved my problem, why I can not vote up ?
    – patel
    Nov 9, 2018 at 12:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.