【发布时间】:2010-08-08 03:42:21
【问题描述】:
我想知道如何导入文本文件。我想导入一个文件,然后逐行读取。
谢谢!
【问题讨论】:
标签: java text import inputstream
我想知道如何导入文本文件。我想导入一个文件,然后逐行读取。
谢谢!
【问题讨论】:
标签: java text import inputstream
我不知道您所说的“导入”文件是什么意思,但这里是使用标准 Java 类逐行打开和读取文本文件的最简单方法。 (这应该适用于所有版本的 Java SE 回到 JDK1.1。使用 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();
}
【讨论】:
【讨论】:
我没明白你所说的“导入”是什么意思。我假设您想读取文件的内容。这是一个示例方法
/** 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);
}
详情可以看here
【讨论】:
Scanner 是在 java 1.5 中引入的。将BufferedReader 用于这些目的已经过时了。
Apache Commons IO 提供了一个很棒的实用程序,称为 LineIterator,可以明确地用于此目的。 FileUtils 类有一个为文件创建一个方法:FileUtils.lineIterator(File)。
这是一个使用示例:
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);
}
【讨论】: