使用Java 8,打印文件中所有行的最优选和最简洁的方式是什么? [英] Using Java 8, what is the most preferred and concise way of printing all the lines in a file?

查看:163
本文介绍了使用Java 8,打印文件中所有行的最优选和最简洁的方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用新的Java 8打印文件中所有行的最佳和最简洁的方法是什么?



输出必须是文件的副本, line for line in:

  [Line 1 ...] 
[Line 2 ...]

这个问题适用于带有lambda的Java-8,尽管在老版本中有这样做的方法。显示Java-8的全部内容!

解决方案

>

我会说这是最优先和简洁的方式,因为:

1)完成后会自动关闭流并适当地抛出任何异常。



2)这个输出是懒惰的。每行都在最后一行处理完毕后读取。这也更接近于原始的基于Java流的文件处理规范。


$ b 3)它以与文件中的数据非常相似的方式打印每一行。 / p>

4)这个内存密集程度较低,因为它不会创建一个像Files.readAllLines(...)这样的中间列表或数组

5)这是最灵活的,因为Stream对象提供了许多用于处理数据(变换,集合,谓词等)的其他用途和函数。

  try(Stream< String> stream = Files.lines(Paths.get(sample.txt),Charset.defaultCharset())){
stream.forEach(的System.out ::的println);





$ b如果提供了路径和字符集,并且消费者可以使用任何对象,工作太:

  try(Stream stream = Files.lines(path,charset)){
stream.forEach的System.out ::的println);

$ / code $ / pre
$ b $ p

使用错误处理:

  try(Stream< String> stream = Files.lines(Paths.get(sample.txt),Charset.defaultCharset())){
stream.forEach (的System.out ::的println);
} catch(IOException ex){
//用异常$ b $做一些事情}


What is the most preferred and concise way to print all the lines in a file using the new 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!

解决方案

This uses the new Stream with a lambda in a try enclosure.

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.

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.

3) It prints each line in a manner that most closely resembles the data in the file.

4) This is less memory intensive because it does not create an intermediate List or Array such as the 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.)

 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
 } 

这篇关于使用Java 8,打印文件中所有行的最优选和最简洁的方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆