在Java中读取文件/输入流内容的最简洁方法是什么?

4

在Java中,读取文件或输入流内容的最简洁方式是什么?我是否总是需要创建缓冲区,逐行读取等等,还是有更简洁的方法?我希望只需执行以下操作:

String content = new File("test.txt").readFully();
10个回答

7
使用Apache Commons IOUtils包。特别是IOUtils类提供了一组方法来从流、读取器等读取,并处理所有的异常等。
例如:
InputStream is = ...
String contents = IOUtils.toString(is);
// or
List lines = IOUtils.readLines(is)

5

我认为在Java内置工具的简洁性方面,使用Scanner是相当不错的选择:

Scanner s = new Scanner(new File("file"));
StringBuilder builder = new StringBuilder();
while(s.hasNextLine()) builder.append(s.nextLine());

此外,它也非常灵活(例如支持正则表达式和数字解析)。


不错的解决方案。比其他所有东西都更简洁。 - Janusz

2

辅助函数。根据情况,我基本上使用其中的几个。

  • cat方法将InputStream传输到OutputStream
  • 调用cat方法将数据传输到ByteArrayOutputStream并提取字节数组的方法,使得可以快速读取整个文件到一个字节数组中
  • 使用Reader构建的Iterator<String>的实现;它将其包装在BufferedReader中,并在next()上进行readLine()
  • ...

要么自己编写,要么使用commons-io或您喜欢的实用程序库中的内容。


1
举一个这样的帮助函数的例子:
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))


1
String content = (new RandomAccessFile(new File("test.txt"))).readUTF();

很不幸,Java对源代码文件的UTF8有效性要求非常严格,否则您将会得到EOFException或UTFDataFormatException异常。


我认为Java对于使用readUTF()读取的文本要求“挑剔”,并不是它存在问题,而是你使用方式有误。请阅读此链接:http://java.sun.com/javase/6/docs/api/java/io/DataInput.html#modified-utf-8。 - Alan Moore

0

从这里选择一个。

如何从文件内容创建Java字符串?

最受欢迎的是:

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();
  }
}

埃里克森发布


0

你得自己创建一个函数,我猜。问题是Java的读取例程(至少我知道的那些)通常需要一个给定长度的缓冲区参数。

我看到的一个解决方案是获取文件的大小,创建一个相同大小的缓冲区,并一次性读取整个文件。希望文件不是一个占用几十亿字节的日志或XML文件...

通常的方法是使用固定大小的缓冲区,或者使用readLine并将结果连接在StringBuffer/StringBuilder中。


0

我认为使用BufferedReader读取数据并不是一个好主意,因为BufferedReader只会返回行内容而不包括分隔符。当行中仅包含换行符时,BR将返回null,尽管它没有到达流的末尾。


不。当 BufferedReader 发现两个连续的换行符时,readLine() 将返回一个空字符串。只有当它到达文件结尾时才返回 null。 - Alan Moore

0

字符串 org.apache.commons.io.FileUtils.readFileToString(File file)


0

或者使用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);
}

可以将适当的字符集传递给字符串构造函数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接