0

I have a text file with the following URLs:

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

I need to read the second line of this TXT, the second URL showed there. I've been researching and I didn't find what I exactly need, because, although I know I have to use the BufferedReader class, I don't know how to specify the "line" I want to read.

This is what I wrote so far:

String fileread = "chlist\\GATHER.txt";
try {                                         
    BufferedReader br = new BufferedReader(new FileReader(fileread));
    String gatherText = br.readLine();
    br.close();
} catch (IOException ioe) {}
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Seba Paz
  • 55
  • 3
  • 9

5 Answers5

1

Each call to br.readLine(); will return you a line from the text file and move you to the next line, so the second call will give you the line you want. The simplest way would be to just write:

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

Although you should also consider what you would do if the file does not contain two lines.

Malcolm Smith
  • 3,540
  • 25
  • 29
0

Use this and you can get the file datas by each line

import org.apache.commons.io.FileUtils; using 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);
}
muthukumar
  • 2,233
  • 3
  • 23
  • 30
0

Try keeping a counter:

final int linesToSkip = 1;
for(int i=0; i<linesToSkip; i++) br.readLine();
String gatherText = br.readLine();
blgt
  • 8,135
  • 1
  • 25
  • 28
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) {}
Anurag Kapur
  • 675
  • 4
  • 19
0

You can use

Apache Commons IO 

and then following code

 String line = FileUtils.readLines(file).get(2);
Makky
  • 17,117
  • 17
  • 63
  • 86