reading tab delimited textfile java

元气小坏坏 提交于 2019-11-28 09:45:46

问题


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

回答1:


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



回答2:


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 ...



来源:https://stackoverflow.com/questions/18331696/reading-tab-delimited-textfile-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!