java 使用 BufferedReader 读取大文本文件并将其存储为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12828938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:22:54  来源:igfitidea点击:

Using BufferedReader to read and store large text file into a String

javastringbufferedreader

提问by ILostMySpoon

Possible Duplicate:
How to create a Java String from the contents of a file

可能的重复:
如何从文件的内容创建 Java 字符串

I am using a BufferedReaderto read a large text file and want to store the entirety of what the reader reads into a String. This does not seem to be working correctly as when I print out the String, it seems as if it only grabbed the last portion of the file. Am I doing something wrong here?

我正在使用 aBufferedReader读取大型文本文件,并希望将读者读取的全部内容存储到String. 这似乎无法正常工作,因为当我打印出 时String,它似乎只抓取了文件的最后一部分。我在这里做错了吗?

String str = "";

try {
    fileReader = new BufferedReader(new FileReader(args[2]));

    try {
        while (fileReader.ready()) {

            str += (char) fileReader.read();

        }

        System.out.println(str);

    } catch (IOException e) {
        e.printStackTrace();
    }
}

回答by Jon Skeet

Am I doing something wrong here?

我在这里做错了吗?

Well, some things wrong, and other things far from ideal.

好吧,有些事情是错误的,有些事情远非理想。

  • You've got a variable of type BufferedReadercalled fileReader. That's confusing to say the least.
  • You're using FileReaderwhich is a generally bad idea as it alwaysuses the platform default encoding
  • You're only reading while ready()returns true. That just returns whether or not the next read will block - it maybe okay for files, but it's definitely not a good idea in general. You should read until the next call indicates that you've exhausted the stream.
  • You're reading a character at a time, which is somewhat inefficient - there's no need to make one call per character rather than using the overload of readwhich takes a character array, allowing bulk transfer.
  • You're using string concatenation to build up the file, which is also very inefficient.
  • There's no indication that you're closing the reader. Maybe that's in code which you haven't posted...
  • You've got two levels of tryblock for no obvious reason, and your IOExceptionhandling is almost always the wrong approach - you should very rarely swallow exceptions (even after logging) and then continue as if nothing happened.
  • 您有一个BufferedReader名为fileReader. 至少可以说这令人困惑。
  • 您正在使用FileReader哪个通常是个坏主意,因为它总是使用平台默认编码
  • 您只是在阅读 whileready()返回true。这只是返回下一次读取是否会阻塞 -文件可能没问题,但总的来说这绝对不是一个好主意。您应该一直阅读,直到下一次调用表明您已经耗尽了流。
  • 您一次读取一个字符,这有点低效 - 不需要对每个字符进行一次调用,而不是使用它的重载read获取字符数组,从而允许批量传输。
  • 您正在使用字符串连接来构建文件,这也非常低效。
  • 没有迹象表明您正在关闭阅读器。也许那是在您尚未发布的代码中...
  • 您有两个级别的try块没有明显的原因,并且您的IOException处理几乎总是错误的方法 - 您应该很少吞下异常(即使在记录之后)然后继续好像什么也没发生一样。

If you possiblycan, avoid writing this code completely - use Guavainstead:

如果可能,请避免完全编写此代码 - 改用Guava

// Use the appropriate encoding for the file, of course.
String text = Files.toString(new File(args[2]), Charsets.UTF_8);

Now of course, you may well find that you still see the same result - maybe the file has "\r"as the line break and you're on a system which onlyinterprets that as "return to start of line" so each line is overwriting the previous one. We can't really tell that - but once you've replaced your code with a single call to Files.toString(), it'll be easier to diagnose that.

当然,现在您很可能会发现您仍然看到相同的结果 - 也许文件有"\r"换行符,而您所在的系统将其解释为“返回行首”,因此每一行都覆盖了前一行一。我们真的不能说——但是一旦你用对 的单个调用替换了你的代码,Files.toString()诊断就会更容易。

回答by Marco Martinelli

Your problem is the while condition. You shouldn't use ready there. By the way, please, replace your String with StringBufferyour code will run much faster.

你的问题是 while 条件。你不应该在那里使用 ready 。顺便说一句,请将您的 String 替换为StringBuffer,您的代码将运行得更快。

Try with this code (untested but should work)

尝试使用此代码(未经测试但应该可以工作)

StringBuffer sb = new StringBuffer();

try {
    fileReader = new BufferedReader(new FileReader(args[2]));
    int i;
    while ((i=fileReader.read())!=-1) {
            sb.append(s);
    }

    System.out.println(sb.toString());

 } catch (IOException e) {
        e.printStackTrace();
 }

Here a version using readLine (if you care about newlines you can still append a \n)

这里有一个使用 readLine 的版本(如果你关心换行符,你仍然可以附加一个 \n)

StringBuffer sb = new StringBuffer();

try {
    fileReader = new BufferedReader(new FileReader(args[2]));
    String s;
    while ((s=fileReader.readLine())!=null) {
            sb.append(s);
            //sb.append('\n'); //if you want the newline
    }

    System.out.println(sb.toString());

 } catch (IOException e) {
        e.printStackTrace();
 }

回答by ali k?ksal

You can also use one of the IOUtils.toString methods of commons ioutils.

您还可以使用 commons ioutils 的 IOUtils.toString 方法之一。

回答by artbristol

If you're on Java 7, use Files.readAllLinesto do this in one line.

如果您使用的是 Java 7,请使用Files.readAllLines一行来完成此操作。

Otherwise, your method is quite inefficient. Use one of the answers from here How do I create a Java string from the contents of a file?

否则,您的方法效率很低。使用这里的答案之一如何从文件的内容创建 Java 字符串?

回答by MByD

If this is a text file, why don't you use readLine()?

如果这是一个文本文件,为什么不使用readLine()