【问题标题】:reading parts of a txt file [duplicate]读取txt文件的部分[重复]
【发布时间】:2013-09-04 14:30:08
【问题描述】:

我有一个包含以下 URL 的文本文件:

http://www.google.com.uy
http://www.google.com.es
http://www.google.com.nz

我需要阅读此 TXT 的第二行,那里显示了第二个 URL。 我一直在研究,并没有找到我真正需要的东西,因为虽然我知道我必须使用BufferedReader 类,但我不知道如何指定我想阅读的“行”。

这是我到目前为止写的:

String fileread = "chlist\\GATHER.txt";
try {                                         
    BufferedReader br = new BufferedReader(new FileReader(fileread));
    String gatherText = br.readLine();
    br.close();
} catch (IOException ioe) {}

【问题讨论】:

  • 记录您阅读的行数。停在第二个。
  • 看看herehere
  • 如果readLine()读了一行文字,需要多少次调用readLine()才能看第二行文字?
  • 当前的两个答案都包含在可能重复的 Q/A 的接受答案中
  • 没有一种通用的方法可以使用 Java 从文件中提取特定行。您必须数数通过。

标签: java


【解决方案1】:

每次调用br.readLine(); 都会从文本文件中返回一行并将您移至下一行,因此第二次调用将为您提供所需的行。最简单的方法是写:

String fileread = "chlist\\GATHER.txt";
    try {                                         
        BufferedReader br = new BufferedReader(new FileReader(fileread));
        br.readLine();
        String gatherText = br.readLine();
        br.close();
} catch (IOException ioe) {}

虽然你也应该考虑如果文件不包含两行你会怎么做。

【讨论】:

    【解决方案2】:

    试着保留一个计数器:

    final int linesToSkip = 1;
    for(int i=0; i<linesToSkip; i++) br.readLine();
    String gatherText = br.readLine();
    

    【讨论】:

      【解决方案3】:
      String fileread = "chlist\\GATHER.txt";
      try {                                         
      BufferedReader br = new BufferedReader(new FileReader(fileread));
      String gatherText;
      int counter = 0;
      while((gatherText = br.readLine()) != null) {
        if(counter ++ == 1) {
          // This is the line you wanted in your example
          System.out.println(gatherText);
        }
      }
      br.close();
      } catch (IOException ioe) {}
      

      【讨论】:

        【解决方案4】:

        你可以使用

        Apache Commons IO 
        

        然后是下面的代码

         String line = FileUtils.readLines(file).get(2);
        

        【讨论】:

          【解决方案5】:

          使用这个可以按每一行获取文件数据

          导入 org.apache.commons.io.FileUtils; 使用 apache-common-io 工具

          try
          {
              List<String> stringList = FileUtils.readLines(new File("chlist\\GATHER.txt"));
              for (String string : stringList)
              {
                  System.out.println("Line String : " + string);
              }
          }
          catch (IOException ex)
          {
              Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
          }
          

          【讨论】:

          • 如果你要推荐外部库,至少要说明它们是什么以及从哪里获得它们。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-04-05
          相关资源
          最近更新 更多