Wayne
Wayne

Reputation: 109

reading tab delimited textfile java

10
aaa aaa aaa
bbb bbb bbb
ccc ccc ccc
ddd ddd ddd

I have a textfile that Im trying to read with tab delimiters. whenever i read the file, i get an arrayindexoutofbound error after the 10. i search online and found that i have to add a -1 behind the \t but i still get the same error.

 try{
        Scanner scan = new Scanner(new File("1.txt"));
        String line="";
        int readline = Integer.parseInt(scan.nextLine());//

        while (scan.hasNextLine())
        {
            line = scan.nextLine();

            if(line.equals("ccc"))
            {  
                break;
            }
        String[] split=line.split("\t");

            array.add(split);
        } 

Upvotes: 2

Views: 21275

Answers (2)

Marc
Marc

Reputation: 2639

This way your code loses this ugly break (break are most of the time avoidable ...)

  try{
    Scanner scan = new Scanner(new File("1.txt"));
    String line="";
    int readline = Integer.parseInt(scan.nextLine());//

    while (scan.hasNextLine())
    {
        line = scan.nextLine();

        if(!line.equals("aaa")){
           String[] split=line.split("\t");
           array.add(split);
        }
    }  

And about your problem I think you are initializing your array with the integer on the first line but it is 10 and you have 12 elements. Thus the index out of bounds but your question remains unclear ...

Upvotes: 0

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35587

If you are use Scanner here no need to split, you can use next() here as follows

    Scanner sc=new Scanner(new FileReader("D:\\test.txt"));
    while (sc.hasNextLine()){
        System.out.println(sc.next());
    }

Upvotes: 12

Related Questions