最简洁的方式来读取Java中的文件/输入流的内容? [英] Most concise way to read the contents of a file/input stream in Java?

查看:196
本文介绍了最简洁的方式来读取Java中的文件/输入流的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中读取文件或输入流内容的最简洁方法是什么?我是否总是要创建缓冲区,逐行读取(最多)等等,还是有更简洁的方法?我希望我能做到这一点

What ist most concise way to read the contents of a file or input stream in Java? Do I always have to create a buffer, read (at most) line by line and so on or is there a more concise way? I wish I could do just

String content = new File("test.txt").readFully();


推荐答案

使用 Apache Commons IOUtils 包。特别是 IOUtils 类提供了一组方法来读取流,读者等,并处理所有异常等。

Use the Apache Commons IOUtils package. In particular the IOUtils class provides a set of methods to read from streams, readers etc. and handle all the exceptions etc.

例如

InputStream is = ...
String contents = IOUtils.toString(is);
// or
List lines = IOUtils.readLines(is)

这篇关于最简洁的方式来读取Java中的文件/输入流的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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