[英]Most concise way to read the contents of a file/input stream in Java?
What ist most concise way to read the contents of a file or input stream in Java? 在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();
Use the Apache Commons IOUtils package. 使用Apache Commons IOUtils包。 In particular the
IOUtils
class provides a set of methods to read from streams, readers etc. and handle all the exceptions etc. 特别是
IOUtils
类提供了一组方法来从流,读取器等中读取并处理所有异常等。
eg 例如
InputStream is = ...
String contents = IOUtils.toString(is);
// or
List lines = IOUtils.readLines(is)
I think using a Scanner is quite OK with regards to conciseness of Java on-board tools: 我认为使用扫描仪在Java板载工具的简洁性方面是相当不错的:
Scanner s = new Scanner(new File("file"));
StringBuilder builder = new StringBuilder();
while(s.hasNextLine()) builder.append(s.nextLine());
Also, it's quite flexible, too (eg regular expressions support, number parsing). 此外,它也非常灵活(例如正则表达式支持,数字解析)。
Helper functions. 助手功能。 I basically use a few of them, depending on the situation
我基本上使用了一些,具体取决于具体情况
Either roll your own or use something out of commons-io or your preferred utility library. 可以自己滚动,也可以使用commons-io或首选实用程序库中的内容。
String content = (new RandomAccessFile(new File("test.txt"))).readUTF();
不幸的是,Java对源文件是有效的UTF8非常挑剔,否则你会得到一个EOFException或UTFDataFormatException。
To give an example of such an helper function: 举一个这样的辅助函数的例子:
String[] lines = NioUtils.readInFile(componentxml);
The key is to try to close the BufferedReader even if an IOException is thrown. 关键是即使抛出IOException,也要尝试关闭BufferedReader。
/**
* Read lines in a file. <br />
* File must exist
* @param f file to be read
* @return array of lines, empty if file empty
* @throws IOException if prb during access or closing of the file
*/
public static String[] readInFile(final File f) throws IOException
{
final ArrayList lines = new ArrayList();
IOException anioe = null;
BufferedReader br = null;
try
{
br = new BufferedReader(new FileReader(f));
String line;
line = br.readLine();
while(line != null)
{
lines.add(line);
line = br.readLine();
}
br.close();
br = null;
}
catch (final IOException e)
{
anioe = e;
}
finally
{
if(br != null)
{
try {
br.close();
} catch (final IOException e) {
anioe = e;
}
}
if(anioe != null)
{
throw anioe;
}
}
final String[] myStrings = new String[lines.size()];
//myStrings = lines.toArray(myStrings);
System.arraycopy(lines.toArray(), 0, myStrings, 0, lines.size());
return myStrings;
}
(if you just want a String, change the function to append each lines to a StringBuffer (or StringBuilder in java5 or 6) (如果你只想要一个String,更改函数以将每一行追加到StringBuffer(或java5或6中的StringBuilder))
You have to create your own function, I suppose. 我想你必须创建自己的功能。 The problem is that Java's read routines (those I know, at least) usually take a buffer argument with a given length.
问题是Java的读取例程(至少我知道)通常采用给定长度的缓冲区参数。
A solution I saw is to get the size of the file, create a buffer of this size and read the file at once. 我看到的解决方案是获取文件的大小,创建一个这样大小的缓冲区并立即读取文件。 Hoping the file isn't a gigabyte log or XML file...
希望该文件不是千兆字节日志或XML文件...
The usual way is to have a fixed size buffer or to use readLine and concatenate the results in a StringBuffer/StringBuilder. 通常的方法是使用固定大小的缓冲区或使用readLine并在StringBuffer / StringBuilder中连接结果。
Or the Java 8 way: 或Java 8方式:
try {
String str = new String(Files.readAllBytes(Paths.get("myfile.txt")));
...
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
One may pass an appropriate Charset to the String constructor. 可以将适当的Charset传递给String构造函数。
I don't think reading using BufferedReader is a good idea because BufferedReader will return just the content of line without the delimeter. 我不认为使用BufferedReader读取是个好主意,因为BufferedReader只会返回没有分隔符的行内容。 When the line contains nothing but newline character, BR will return a null although it still doesn't reach the end of the stream.
当该行只包含换行符时,BR将返回null,尽管它仍未到达流的末尾。
String org.apache.commons.io.FileUtils.readFileToString(文件文件)
Pick one from here. 从这里选择一个。
How do I create a Java string from the contents of a file? 如何从文件内容创建Java字符串?
The favorite was: 最喜欢的是:
private static String readFile(String path) throws IOException {
FileInputStream stream = new FileInputStream(new File(path));
try {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
/* Instead of using default, pass in a decoder. */
return CharSet.defaultCharset().decode(bb).toString();
}
finally {
stream.close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.