Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

java - How to reset Scanner?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...