[英]Using Java 8, what is the most preferred and concise way of printing all the lines in a file?
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. 问题涉及带有lambdas的Java-8,即使在旧版本中有这样的方法。 Show what Java-8 is all about!
展示Java-8的全部内容!
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. 2)这个输出是懒惰的。 Each line is read after the last line is processed.
在处理完最后一行之后读取每一行。 This is also is closer to the original Java streams based file handling spec.
这也更接近原始的基于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: 如果提供了路径和字符集,并且Consumer可以使用任何Object,那么这也适用:
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
}
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);
这是一个简单的解决方案:
System.out.println( new String(Files.readAllBytes(Paths.get("sample.java"))) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.