导入文本文件并在Java中逐行读取

时间:2010-08-08 03:42:21

标签: java text import inputstream

我想知道如何导入文本文件。我想导入一个文件,然后逐行阅读。

谢谢!

4 个答案:

答案 0 :(得分:12)

我不知道“导入”文件是什么意思,但这是使用标准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();
}

答案 1 :(得分:9)

答案 2 :(得分:4)

我没有得到'import'的意思。我假设您要阅读文件的内容。这是一个做它的示例方法

  /** 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

答案 3 :(得分:0)

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);
}
相关问题