0

I have this code below.What i'm trying to do is read a text file which every line has Strings separated by tabs.For example (name \t country \t id \t content) where \t is the tab.Then i want to print only the 2nd column of each line.I'm trying split the whole line to tokens but it works fine only for the 1st line of the file and then it throws ArrayIndexOutOfBoundsException. Also it works perfect when i try to print only the 1st column (tokens[0]) but not for tokens[1] which I need.So what am I need to do to get the 2nd columns of each line?

public static void main(String[] args) throws FileNotFoundException, IOException
{
    FileInputStream fis=new FileInputStream("a.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(dis)) ;
    String line;
    while ((line = br.readLine()) != null) 
    {
        String[] tokens=line.split("\\t");
        System.out.println(tokens[1]);  

    }
    fis.close();
}  
Jack21
  • 21
  • 6

3 Answers3

1

If the line looks for example like this

asdf\t\t\t

Then you have a problem. You should use

String[] tokens=line.split("\\t", -1);

See Java: String split(): I want it to include the empty strings at the end

Community
  • 1
  • 1
radoh
  • 4,554
  • 5
  • 30
  • 45
0

if no tab exists in the line you get the exception.

you should check if tokens.length()>1 before accessing the second element.

Jens
  • 67,715
  • 15
  • 98
  • 113
0

Java 8 :

    try (Stream<String> stream = Files.lines(Paths.get("a.txt"))) {
        stream.map(line -> line.split("\\t"))
                .filter(tokens -> tokens.length > 1)
                .forEach(tokens -> System.out.println(tokens[1]));
    } catch (IOException e) {
        e.printStackTrace();
    }
Bax
  • 4,260
  • 5
  • 43
  • 65