从txt读取文件并使用逗号分割字符串

时间:2014-01-05 13:56:32

标签: java split

为什么说没有找到拆分方法?我想将一行分成几个部分。但是有错误。为什么会这样 ?

 try {
        Scanner a = new Scanner (new FileInputStream ("product.txt"));

        while (a.hasNext()){
            System.out.println(a.nextLine()); //this works correctly, all the lines are displayed
            String[] temp = a.split(",");

        }
        a.close();

    }catch (FileNotFoundException e){
        System.out.println("File not found");
    }

2 个答案:

答案 0 :(得分:4)

split()未定义为Scanner,而是针对String

这是一个快速修复:

        String line = a.nextLine();
        System.out.println(line); //this works correctly, all the lines are displayed
        String[] temp = line.split(",");

答案 1 :(得分:2)

split方法适用于String,而不适用于Scanner。所以存储

的内容
a.nextLine()

在像这样的字符串中

String line = a.nextLine();

然后在这个搅拌上使用拆分方法

String[] temp = line.split(",");