在Java中,读取文件或输入流内容的最简洁方式是什么?我是否总是需要创建缓冲区,逐行读取等等,还是有更简洁的方法?我希望只需执行以下操作:
String content = new File("test.txt").readFully();
在Java中,读取文件或输入流内容的最简洁方式是什么?我是否总是需要创建缓冲区,逐行读取等等,还是有更简洁的方法?我希望只需执行以下操作:
String content = new File("test.txt").readFully();
IOUtils
类提供了一组方法来从流、读取器等读取,并处理所有的异常等。InputStream is = ...
String contents = IOUtils.toString(is);
// or
List lines = IOUtils.readLines(is)
我认为在Java内置工具的简洁性方面,使用Scanner是相当不错的选择:
Scanner s = new Scanner(new File("file"));
StringBuilder builder = new StringBuilder();
while(s.hasNextLine()) builder.append(s.nextLine());
此外,它也非常灵活(例如支持正则表达式和数字解析)。
辅助函数。根据情况,我基本上使用其中的几个。
要么自己编写,要么使用commons-io或您喜欢的实用程序库中的内容。
String[] lines = NioUtils.readInFile(componentxml);
关键是尝试关闭 BufferedReader,即使抛出 IOException 异常。
/**
* 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;
}
(如果您只需要一个字符串,请将函数更改为将每行附加到StringBuffer(或Java5或6中的StringBuilder))
String content = (new RandomAccessFile(new File("test.txt"))).readUTF();
很不幸,Java对源代码文件的UTF8有效性要求非常严格,否则您将会得到EOFException或UTFDataFormatException异常。
从这里选择一个。
最受欢迎的是:
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();
}
}
由埃里克森发布
你得自己创建一个函数,我猜。问题是Java的读取例程(至少我知道的那些)通常需要一个给定长度的缓冲区参数。
我看到的一个解决方案是获取文件的大小,创建一个相同大小的缓冲区,并一次性读取整个文件。希望文件不是一个占用几十亿字节的日志或XML文件...
通常的方法是使用固定大小的缓冲区,或者使用readLine并将结果连接在StringBuffer/StringBuilder中。
我认为使用BufferedReader读取数据并不是一个好主意,因为BufferedReader只会返回行内容而不包括分隔符。当行中仅包含换行符时,BR将返回null,尽管它没有到达流的末尾。
字符串 org.apache.commons.io.FileUtils.readFileToString(File file)
或者使用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);
}
可以将适当的字符集传递给字符串构造函数。