最简洁的方法来读取Java中的文件/输入流的内容?

时间:2008-10-22 09:05:29

标签: java

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

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

10 个答案:

答案 0 :(得分:7)

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

e.g。

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

答案 1 :(得分:5)

我认为使用扫描仪对于Java板载工具的简洁性非常好:

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

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

答案 2 :(得分:2)

辅助功能。我基本上使用了一些,具体取决于具体情况

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

自行滚动或使用commons-io或首选实用程序库中的内容。

答案 3 :(得分:1)

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

不幸的是,Java对源文件是有效的UTF8非常挑剔,否则你会得到EOFException或UTFDataFormatException。

答案 4 :(得分:1)

举一个这样的辅助函数的例子:

String[] lines = NioUtils.readInFile(componentxml);

关键是即使抛出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;
}

(如果你只想要一个String,更改函数以将每一行追加到StringBuffer(或java5或6中的StringBuilder)

答案 5 :(得分:0)

我想你必须创建自己的功能。问题是Java的读取例程(我知道,至少)通常采用给定长度的缓冲区参数。

我看到的解决方案是获取文件的大小,创建一个这样大小的缓冲区并立即读取文件。希望该文件不是千兆字节日志或XML文件......

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

答案 6 :(得分:0)

我不认为使用BufferedReader读取是个好主意,因为BufferedReader只返回没有分隔符的行内容。当该行只包含换行符时,BR将返回null,尽管它仍然没有到达流的末尾。

答案 7 :(得分:0)

String org.apache.commons.io.FileUtils.readFileToString(File file)

答案 8 :(得分:0)

从这里选择一个。

How do I create a Java string from the contents of a file?

最喜欢的是:

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

erickson发布

答案 9 :(得分: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);
}

可以将适当的Charset传递给String构造函数。