读取txt文件的一部分

时间:2013-09-04 14:30:08

标签: java

我有一个包含以下网址的文字文件:

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

5 个答案:

答案 0 :(得分: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) {}

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

答案 1 :(得分:0)

使用此选项,您可以按行获取文件数据

import org.apache.commons.io.FileUtils; 使用apache-common-io utils

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

答案 2 :(得分:0)

尝试保留一个柜台:

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

答案 3 :(得分:0)

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 :(得分:0)

您可以使用

Apache Commons IO 

然后是代码

 String line = FileUtils.readLines(file).get(2);
相关问题