How to reset Scanner?

左心房为你撑大大i 提交于 2019-12-14 00:10:26

问题


I want to read a text file and put each line in a String (array of Strings). However that requires scanning file twice, one to figure out how many line are there and another time to create an array of strings of that size. but it throws an error and reset method doesn't seem to work.

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

This is the snippet of the code that is relevant.


回答1:


Skip using a standard array... it's a waste of time to scan through the file and then scan through again. Use an arraylist instead which has a dynamic size and then convert it to a standard array afterwards.

 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:


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

No it doesn't. See @Exziled's answer for a better (simpler, more efficient) way that doesn't scan the file twice.

But to answer your question, there is no way to reset a Scanner to the start of the stream. You would need to reset the underlying stream and then create a new Scanner. (And, of course, some kinds of stream don't support resetting.)

For the record, the Scanner.reset() method resets the scanner's delimiter, locale and number radix state. It doesn't reposition the scanner.



来源:https://stackoverflow.com/questions/34822927/how-to-reset-scanner

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