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

在Java中读取文件/输入流内容的最简洁的方法?,java,Java,在Java中,读取文件或输入流内容最简洁的方法是什么?我总是要创建一个缓冲区,逐行读取(最多)等等,还是有更简洁的方法?我希望我能做到 String content = new File("test.txt").readFully(); 不幸的是,Java非常挑剔源文件是否为有效的UTF8,否则您将得到一个EOFEException或UTFDataFormatException。我想您必须创建自己的函数。问题是Java的读取例程(至少我知道的)通常使用给定长度的缓冲区参数 我看到的一个解决方案

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

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

不幸的是,Java非常挑剔源文件是否为有效的UTF8,否则您将得到一个EOFEException或UTFDataFormatException。

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

我看到的一个解决方案是获得文件的大小,创建一个这个大小的缓冲区,然后立即读取文件。希望该文件不是GB日志或XML文件


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

辅助函数。根据具体情况,我基本上会使用其中的一些

  • 通过管道将InputStream传输到OutputStream的cat方法
  • 方法,该方法对ByteArrayOutputStream调用cat并提取字节数组,从而能够将整个文件快速读取到字节数组
  • 使用读取器构造的迭代器的实现;它将其包装在一个BufferedReader中,readLine位于next()上

您可以使用自己的或使用commons io或您首选的实用程序库中的内容。

举一个此类帮助函数的示例:

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;
}
/**
*读取文件中的行
*文件必须存在 *@param f要读取的文件 *@返回行数组,如果文件为空则为空 *@在访问或关闭文件时,如果prb出现异常,则会引发IOException */ 公共静态字符串[]readinfle(最终文件f)引发IOException { 最终ArrayList行=新ArrayList(); ioe=null; BufferedReader br=null; 尝试 { br=新的BufferedReader(新的文件读取器(f)); 弦线; line=br.readLine(); while(行!=null) { 行。添加(行); line=br.readLine(); } br.close(); br=null; } 捕获(最终IOE例外) { anioe=e; } 最后 { 如果(br!=null) { 试一试{ br.close(); }捕获(最终IOE例外){ anioe=e; } } 如果(anioe!=null) { 扔给阿尼奥; } } 最终字符串[]myStrings=新字符串[lines.size()]; //myStrings=lines.toArray(myStrings); 数组复制(lines.toArray(),0,myString,0,lines.size()); 返回我的字符串; }

(如果您只需要一个字符串,请将函数更改为将每一行附加到StringBuffer(或java5或6中的StringBuilder)中)

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

String org.apache.commons.io.FileUtils.readFileToString(文件文件)

我认为使用扫描器对于Java车载工具的简洁性来说是很好的:

Scanner s = new Scanner(new File("file"));
StringBuilder builder = new StringBuilder();
while(s.hasNextLine()) builder.append(s.nextLine());
此外,它也非常灵活(例如,正则表达式支持数字解析)。

从这里选择一个

最受欢迎的是:

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();
  }
}
发布者使用该包。尤其是
IOUtils
类提供了一组方法来读取流、读卡器等,并处理所有异常等

e、 g

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

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

我认为Java对您使用readUTF()读取的文本“挑剔”不是问题,只是您使用了错误的字符集。请阅读以下内容:否。当BufferedReader看到两个连续的行分隔符时,readLine()返回一个空字符串。它仅在到达文件结尾时返回null。很好的解决方案。比其他所有内容都更干净
InputStream is = ...
String contents = IOUtils.toString(is);
// or
List lines = IOUtils.readLines(is)
try {
    String str = new String(Files.readAllBytes(Paths.get("myfile.txt")));
    ...
} catch (IOException ex) {
    Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}