有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何重置扫描仪?

我想读取一个文本文件,并将每一行放入一个字符串(字符串数组)。然而,这需要扫描文件两次,一次是计算出有多少行,另一次是创建一个这样大小的字符串数组。但它抛出了一个错误,重置方法似乎不起作用

    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) 个答案

  1. # 1 楼答案

    跳过使用标准数组。。。扫描文件然后再扫描一遍是浪费时间。使用具有动态大小的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]);
    
  2. # 2 楼答案

    "However that requires scanning file twice ..." ...

    不,没有。请参阅@Exziled的答案,了解一种更好(更简单、更高效)的方法,该方法不会扫描文件两次

    但是要回答您的问题,没有办法将Scanner重置为流的开头。您需要重置底层流,然后创建一个新的Scanner。(当然,某些类型的流不支持重置。)

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