导入文本文件并在 Java 中逐行读取
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3432970/
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
Import Textfile and read line by line in Java
提问by Jeff
I was wondering how one would go about importing a text file. I want to import a file and then read it line by line.
我想知道如何导入文本文件。我想导入一个文件,然后一行一行地读取它。
thanks!
谢谢!
回答by Tansir1
This should cover just about everything you need.
这应该涵盖您需要的几乎所有内容。
http://download.oracle.com/javase/tutorial/essential/io/index.html
http://download.oracle.com/javase/tutorial/essential/io/index.html
And for a specific example: http://www.java-tips.org/java-se-tips/java.io/how-to-read-file-in-java.html
对于一个具体的例子:http: //www.java-tips.org/java-se-tips/java.io/how-to-read-file-in-java.html
This might also help: Read text file in Java
这也可能有帮助:Read text file in Java
回答by Stephen C
I've no idea what you mean by "importing" a file, but here's the simplest way to open and read a text file line by line, using just standard Java classes. (This should work for all versions of Java SE back to JDK1.1. Using Scanner is another option for JDK1.5 and later.)
我不知道“导入”文件是什么意思,但这里是仅使用标准 Java 类逐行打开和读取文本文件的最简单方法。(这应该适用于回到 JDK1.1 的所有 Java SE 版本。使用 Scanner 是 JDK1.5 及更高版本的另一个选项。)
BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(fileName)));
try {
String line;
while ((line = br.readLine()) != null) {
// process line
}
} finally {
br.close();
}
回答by Gopi
I didnt get what you meant by 'import'. I assume you want to read contents of a file. Here is an example method that does it
我没有明白你所说的“进口”是什么意思。我假设您想读取文件的内容。这是一个执行此操作的示例方法
/** Read the contents of the given file. */
void read() throws IOException {
System.out.println("Reading from file.");
StringBuilder text = new StringBuilder();
String NL = System.getProperty("line.separator");
Scanner scanner = new Scanner(new File(fFileName), fEncoding);
try {
while (scanner.hasNextLine()){
text.append(scanner.nextLine() + NL);
}
}
finally{
scanner.close();
}
System.out.println("Text read in: " + text);
}
For details you can see here
有关详细信息,您可以在此处查看
回答by mwooten.dev
Apache Commons IOoffers a great utility called LineIterator that can be used explicitly for this purpose. The class FileUtils has a method for creating one for a file: FileUtils.lineIterator(File).
Apache Commons IO提供了一个很棒的实用程序,称为 LineIterator,可以明确地用于此目的。FileUtils 类有一个为文件创建一个的方法:FileUtils.lineIterator(File)。
Here's an example of its use:
下面是它的使用示例:
File file = new File("thing.txt");
LineIterator lineIterator = null;
try
{
lineIterator = FileUtils.lineIterator(file);
while(lineIterator.hasNext())
{
String line = lineIterator.next();
// Process line
}
}
catch (IOException e)
{
// Handle exception
}
finally
{
LineIterator.closeQuietly(lineIterator);
}