如何重置扫描仪?

时间:2016-01-16 02:33:52

标签: java java.util.scanner nosuchelementexception

我想读取一个文本文件并将每一行放在一个String(字符串数组)中。然而,这需要两次扫描文件,一个用于计算有多少行,另一个用于创建该大小的字符串数组。但它会引发错误。并且重置方法似乎不起作用。

        FileReader read = null;
    try {
        read = new FileReader("ModulesIn.txt");
        //scan through it and make array of strings - for each line
        Scanner scan = new Scanner(read);
        while(scan.hasNextLine())
        {
            numOfMods++;
            scan.nextLine();
        }

        scan.reset();

        lines = new String[numOfMods];

        for(int i = 0; i < numOfMods; i++)
            lines[i] = scan.nextLine();

这是相关代码的缩影。

2 个答案:

答案 0 :(得分:4)

使用标准阵列跳过...扫描文件然后再次扫描是浪费时间。使用具有动态大小的arraylist,然后将其转换为标准数组。

 BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
        String str;

        List<String> list = new ArrayList<String>();
        while((str = in.readLine()) != null){
            list.add(str);
        }

        String[] stringArr = list.toArray(new String[0]);

答案 1 :(得分:1)

  

“但是这需要扫描文件两次......”......

不,不。请参阅@ Exziled的答案,了解更好(更简单,更高效)的方式,不会扫描文件两次。

但要回答您的问题,无法将Scanner重置为流的开头。您需要重置基础流,然后创建新的Scanner。 (当然,某些类型的流不支持重置。)

对于记录,Scanner.reset()方法重置扫描程序的分隔符,区域设置和数字基数状态。它不会重新定位扫描仪。