0

我试图从一个文本文件中拆分一些字符串,该文件在整数之间有制表符。整数 /t 整数 /t 整数。

50      

1   2   46

1   15  38

1   16  43

1   21  4

1   25  24

1   35  2

1   43  6

我尝试使用字符串令牌但ArrayIndexOutOfBoundsException出来了,所以我自己做了一些调试并发现了这一点。

我的代码如何:

public static void main(String[] args) throws FileNotFoundException {
    Scanner input = new Scanner(new File("Datas.txt"));
    String data;
    int i = 0;

    while (input.hasNextLine()) {
        data = input.nextLine();
        String[] sp = data.split("\\t+");

        String n1 = sp[0];
        System.out.println("|" + n1 + "|");
    }
    input.close();
}

这是我编译并运行它时结果的图片链接。在此处输入图像描述

编辑:不知道为什么结果会这样。切换到 bufferedReader 现在一切都很好。感谢人们的帮助。

4

4 回答 4

0

我会做的更简单

    while (sc.hasNext()) {
        String next = sc.next();
    }

它被空格和换行符打破

于 2013-08-13T09:45:48.127 回答
0

您可能不会使用 Scanner#nextInt() 方法。

File f = new File("Datas.txt");
Scanner scanner = null;

try {
    scanner = new Scanner(f);

    while (scanner.hasNextInt()) {
        System.out.println(scanner.nextInt());
    }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (scanner != null) {
       scanner.close();
    }
}
于 2013-08-13T09:45:10.493 回答
0

这应该正确拆分

while(input.hasNextLine())
{
    data = input.nextLine();
    String [] sp = data.split("\\s+");
    if(sp.lenght>1){
     String n1 = "|";
     for(String tmp:sp){
         n1=n1.concat(h);
     }
     n1=n1.concat("|");
     System.out.println(n1);
    }
}
于 2013-08-13T09:39:21.857 回答
0

更改您的代码如下

public static void main (String []args) throws FileNotFoundException {
    Scanner input = new Scanner(new File("D:\\sample.txt"));
    String data;
    int i = 0;
    while(input.hasNextLine())
    {
        data = input.nextLine();
        String [] sp = data.split("\t");
        String n1 = sp[0];
        System.out.println("|" + n1 + "|" );
    }
    input.close();
}
于 2013-08-13T09:41:18.630 回答