2017-09-01 73 views
0

以下是文件内容:读取文件的Java 8

line 1 
line 2 
line 3 
line 4 
line 5 

现在我想读以相反的顺序串的文件,如下

line 5 
line 4 
line 3 
line 2 
line 1 

我用它来阅读代码逐行文件是

try (Stream<String> steam = Files.lines(Paths.get("C:\\..\\..\\taxreport.txt")).skip(1)) { 
    steam.foreach(i->System.Out.Println(i)); 
} 
catch (IOException ex) { 
    System.out.println(RED_BOLD + "File not Found !!"); 
} 

代码以正常顺序逐行读取文件。但我想按相反的顺序阅读该行。

任何人都可以让我知道如何以相反的顺序读取行。

+3

的可能的复制[如何读取最终文件中的Java启动(以相反的顺序)?] (https://stackoverflow.com/questions/8664705/how-to-read-file-from-end-to-start-in-reverse-order-in-java) – soorapadman

+1

[Java 8流反向顺序]的可能重复(https://stackoverflow.com/questions/24010109/java-8-stream-reverse-order) – Jotunacorn

+2

你需要重新d文件,将其存储在LIFO集合中,然后阅读该集合。您并没有真正的“简单”方法来将光标定位到文件中。所以这将在记忆中完成。 – AxelH

回答

1

这适用于字符串:

steam.collect(Collectors.toCollection(LinkedList::new)) 
    .descendingIterator().forEachRemaining(System.out::println); 

这是使用ArrayList另一个例子:

List<String> list = steam.collect(Collectors.toCollection(ArrayList::new)); 
    Collections.reverse(list); 
    list.forEach(System.out::println); 
+0

我们能不能在这里使用Stack? –

+0

@HimanshuBhardwaj我不确定你的意思,但我又添了一个例子。 –

+0

忽略我,在这里找到了我的问题的答案。 https://stackoverflow.com/questions/30387579/stack-using-the-java-8-collection-streaming-api –