如何使用 Java 中的缓冲阅读器再次读取文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3852276/
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
How do I read a file again using buffered reader in Java?
提问by Harish
I have a Java code that reads through an input file using a buffer reader until the readLine()
method returns null
. I need to use the contents of the file again indefinite number of times. How can I read this file from beginning again?
我有一个 Java 代码,它使用缓冲区读取器读取输入文件,直到该readLine()
方法返回null
。我需要无限次地再次使用文件的内容。我怎样才能从头开始阅读这个文件?
采纳答案by afian
you do this by calling the run() function recursively, after checking to see if no more lines can be read - here's a sample
您可以通过递归调用 run() 函数来完成此操作,在检查是否无法读取更多行之后 - 这是一个示例
// Reload the file when you reach the end (i.e. when you can't read anymore strings)
if ((sCurrentLine = br.readLine()) == null) {
run();
}
回答by matiasg
You can close and reopen it again. Another option: if it is not too large, put its content into, say, a List.
您可以关闭并重新打开它。另一种选择:如果它不是太大,则将其内容放入一个列表中。
回答by pinichi
Buffer reader supports reset() to a position of buffered data only. But this cant goto the begin of file (suppose that file larger than buffer).
Solutions:
1.Reopen
2.Use RandomAccessFile
缓冲区读取器仅支持 reset() 到缓冲数据的位置。但这不能转到文件的开头(假设该文件大于缓冲区)。
解决方案:
1.Reopen 2.Use
RandomAccessFile
回答by ColinD
A single Reader
should be used once to read the file. If you want to read the file again, create a new Reader
based on it.
Reader
应该使用单个来读取文件。如果您想再次读取该文件,请Reader
根据它创建一个新文件。
Using Guava's IO utilities, you can create a nice abstraction that lets you read the file as many times as you want using Files.newReaderSupplier(File, Charset). This gives you an InputSupplier<InputStreamReader>that you can retrieve a new Reader
from by calling getInput()
at any time.
使用Guava的 IO 实用程序,您可以创建一个很好的抽象,让您可以使用Files.newReaderSupplier(File, Charset)根据需要多次读取文件。这为您提供了一个InputSupplier<InputStreamReader>,您可以随时Reader
通过调用从中检索一个新的getInput()
。
Even better, Guava has many utility methods that make use of InputSupplier
s directly... this saves you from having to worry about closing the supplied Reader
yourself. The CharStreamsclass contains most of the text-related IO utilities. A simple example:
更好的是,Guava 有许多实用方法可以InputSupplier
直接使用s ……这让您不必担心自己关闭所提供的Reader
。该CharStreams类包含的文本相关的IO事业最。一个简单的例子:
public void doSomeStuff(InputSupplier<? extends Reader> readerSupplier) throws IOException {
boolean needToDoMoreStuff = true;
while (needToDoMoreStuff) {
// this handles creating, reading, and closing the Reader!
List<String> lines = CharStreams.readLines(readerSupplier);
// do some stuff with the lines you read
}
}
Given a File
, you could call this method like:
给定 a File
,你可以像这样调用这个方法:
File file = ...;
doSomeStuff(Files.newReaderSupplier(file, Charsets.UTF_8)); // or whatever charset
If you want to do some processing for each line without reading every line into memory first, you could alternatively use the readLines
overload that takes a LineProcessor.
如果您想对每一行进行一些处理而不先将每一行读入内存,您也可以使用readLines
采用LineProcessor的重载。
回答by Saurabh Patil
I faced with the same issue and came wandering to this question.
我遇到了同样的问题,并徘徊在这个问题上。
1. Using mark() and reset() methods:
1. 使用 mark() 和 reset() 方法:
BufferedReader can be created using a FileReader and also a FileInputStream. FileReader doesn't support Mark and Reset methods. I got an exception while I tried to do this. Even when I tried with FileInputStream I wasn't able to do it because my file was large (even your's is I guess). If the file length is larger than the buffer then mark and reset methods won't work neither with FileReader not with FileInputStream. More on this in this answerby @jtahlborn.
BufferedReader 可以使用 FileReader 和 FileInputStream 创建。FileReader 不支持 Mark 和 Reset 方法。我尝试这样做时遇到了一个例外。即使当我尝试使用 FileInputStream 时我也无法做到,因为我的文件很大(我猜甚至你的文件也是如此)。如果文件长度大于缓冲区,则标记和重置方法既不适用于 FileReader,也不适用于 FileInputStream。在@jtahlborn 的这个答案中有更多关于这个的信息。
2. Closing and reopening the file
2. 关闭并重新打开文件
When I closed and reopened the file and created a new BufferedReader, it worked well. The ideal way I guess is to reopen the file again and construct a new BufferedReader as a FileReader or FileInputStream should be used only once to read the file.
当我关闭并重新打开文件并创建一个新的 BufferedReader 时,它运行良好。我猜的理想方法是再次重新打开文件并构造一个新的 BufferedReader 作为 FileReader 或 FileInputStream 应该只使用一次来读取文件。
回答by QuadBiker
try {
BufferedReader br = new BufferedReader(new FileReader(input));
while ((line = br.readLine()) != null)
{
//do somethng
}
br.close();
}
catch(IOException e)
{
System.err.println("Error: " + e.getMessage());
}
}
回答by JoshD
If you want to do this, you may want to consider a random access file. With that you can explicitly set the position back to the beginning and start reading again from there.
如果你想这样做,你可能需要考虑一个随机访问文件。有了它,您可以明确地将位置设置回开头并从那里重新开始阅读。
回答by Aaron Saunders
i would suggestion usings commons libraries
我建议使用公共图书馆
http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html
http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html
i think there is a call to just read the file into a byteArray which might be an alternate approach
我认为有一个调用只是将文件读入 byteArray,这可能是另一种方法
回答by kartheek
Not sure if you have considered the mark()
and reset()
methods on the BufferedReader
不确定您是否考虑过BufferedReader上的mark()
和reset()
方法
that can be an option if your files are only a few MBs in size and you can set the mark at the beginning of the file and keep reset()ing once you hit the end of the file. It also appears that subsequent reads on the same file will be served entirely from the buffer without having to go to the disk.
如果您的文件只有几 MB 大小,并且您可以在文件的开头设置标记,并在到达文件末尾时保持 reset(),那么这可能是一个选项。似乎对同一文件的后续读取将完全从缓冲区提供服务,而无需转到磁盘。