使用 Java 8,打印文件中所有行的最首选和最简洁的方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19605151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Java 8, what is the most preferred and concise way of printing all the lines in a file?
提问by The Coordinator
What is the most preferred and concise way to print all the lines in a file using the new Java 8?
使用新的 Java 8 打印文件中所有行的最首选和最简洁的方法是什么?
The output must be a copy of the file, line for line as in:
输出必须是文件的副本,一行一行,如下所示:
[Line 1 ...]
[Line 2 ...]
The question pertains to Java-8 with lambdas even though there are ways of doing it in older versions. Show what Java-8 is all about!
该问题与带有 lambda 的 Java-8 相关,即使在旧版本中有办法做到这一点。展示 Java-8 的全部内容!
采纳答案by The Coordinator
This uses the new Stream with a lambda in a try enclosure.
这在 try 外壳中使用带有 lambda 的新 Stream。
I would say it is the most preferred and concise way because:
我会说这是最首选和最简洁的方式,因为:
1) It will automatically close the stream when done and properly throw any exceptions.
1) 完成后会自动关闭流并正确抛出任何异常。
2) The output of this is lazy. Each line is read after the last line is processed. This is also is closer to the original Java streams based file handling spec.
2) this 的输出是惰性的。在处理完最后一行之后读取每一行。这也更接近于原始的基于 Java 流的文件处理规范。
3) It prints each line in a manner that most closely resembles the data in the file.
3) 它以最接近文件中数据的方式打印每一行。
4) This is less memory intensive because it does not create an intermediate List or Array such as the Files.readAllLines(...)
4) 这较少占用内存,因为它不会创建中间列表或数组,例如 Files.readAllLines(...)
5) This is the most flexible, since the Stream object provided has many other uses and functions for working with the data (transforms, collections, predicates, etc.)
5) 这是最灵活的,因为提供的 Stream 对象还有许多其他用途和功能来处理数据(转换、集合、谓词等)
try (Stream<String> stream = Files.lines(Paths.get("sample.txt"),Charset.defaultCharset())) {
stream.forEach(System.out::println);
}
If the path and charset are provided and the Consumer can take any Object then this works too:
如果提供了路径和字符集并且消费者可以使用任何对象,那么这也适用:
try (Stream stream = Files.lines(path,charset)) {
stream.forEach(System.out::println);
}
With error handling:
带有错误处理:
try (Stream<String> stream = Files.lines(Paths.get("sample.txt"),Charset.defaultCharset())) {
stream.forEach(System.out::println);
} catch (IOException ex) {
// do something with exception
}
回答by assylias
You don't really need Java 8:
你真的不需要 Java 8:
System.out.println(Files.readAllLines(path, charset));
If you really want to use a stream or need a cleaner presentation:
如果您真的想使用流或需要更清晰的演示:
Files.readAllLines(path, charset).forEach(System.out::println);
回答by Nery Jr
Here is a simple solution:
这是一个简单的解决方案:
System.out.println( new String(Files.readAllBytes(Paths.get("sample.java"))) );