【问题标题】:Import Textfile and read line by line in Java导入文本文件并在Java中逐行读取
【发布时间】:2010-08-08 03:42:21
【问题描述】:

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

谢谢!

【问题讨论】:

    标签: java text import inputstream


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      【讨论】:

      • 这正是我所需要的。谢谢!
      【解决方案3】:

      我没明白你所说的“导入”是什么意思。我假设您想读取文件的内容。这是一个示例方法

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

      【讨论】:

      • 扫描仪?是不是有点老了?
      • @Lord Quackstar:Scanner 是在 java 1.5 中引入的。将BufferedReader 用于这些目的已经过时了。
      【解决方案4】:

      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);
      }
      

      【讨论】:

      • 对于 BufferedFileReader 而言,这听起来有点矫枉过正。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 2015-10-25
      相关资源
      最近更新 更多