Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Reuse same Scanner to read another file

  1. #1
    Junior Member
    Join Date
    Apr 2013
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Reuse same Scanner to read another file

    Hi everyone
    thanks in advance for patience and taking the time to read my code
    I am trying to get one Scanner to read from 2 files i.e.
    Read from file1 then count contents make count the size of arr1 (size1), fill arr1 with file1
    Reset Scanner and repeat for file2 and arr2
    Do I need another scanner?
    If I do what is the scanner.reset() for?

    Here is my code so far
    import java.util.Scanner;
    import java.io.File;
    import java.io.FileNotFoundException;
     
    public class FindInArray{
     
    	public static void main(String [] args){
     
    	int [] arr1 = new int[0];
    	int [] arr2 = new int[0];
    	int size1 = 0;
    	int size2 = 0;
    	Scanner sc = new Scanner(System.in);
    	System.out.println("Enter the filename");
    	String file1 = sc.nextLine();
    	System.out.println("Enter another filename");
    	String file2 = sc.nextLine();
    	try{
    		Scanner ns = new Scanner(new File(file1));
    		while(ns.hasNextInt()&&ns.nextInt()!= -1){
    			size1++;
    		}
    		ns.reset();
    		arr1 = new int[size1];
    		System.out.println(size1);
    		int x = 0;
    		while(x<arr1.length&&ns.nextInt()!= -1){
    			arr1[x] = ns.nextInt();
    			x++;
    		}
    		ns.reset();
    		x = 0;
    		ns = Scanner(new File(file2));
    		while(ns.hasNextInt()&&ns.nextInt()!= -1){
    			size2++;
    		}
    		arr2 = new int[size2];
    		while(x<arr2.length&&ns.nextInt()!= -1){
    			arr2[x] = ns.nextInt();
    			x++;
    		}
    	}
    	catch(FileNotFoundException e) {
    			System.out.println("That file was not found. Program terminating...");
    			e.printStackTrace();
    	}
    Last edited by pbrockway2; April 1st, 2013 at 05:47 PM. Reason: code tags added


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Reuse same Scanner to read another file

    Why do you want to reuse a Scanner?

    --- Update ---

    I moved this post to a more appropriate forum. Please read this: http://www.javaprogrammingforums.com...e-posting.html
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    Member
    Join Date
    Sep 2012
    Posts
    128
    Thanks
    1
    Thanked 14 Times in 14 Posts

    Default Re: Reuse same Scanner to read another file

    The reset() method will reset the value of the scanner's radix to 10 regardless of whether it was previously changed. (ref)

    Does your program work or what is the error message?

  4. #4
    Junior Member
    Join Date
    Apr 2013
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Reuse same Scanner to read another file

    Thought it would be good practice to use the same Scanner if possible instead of creating another object, I used it initially to count the number of items in the File to use this count as the array size to store the file contents in, then I wanted to go back to the beginning of the file to start reading in again this time storing the file contents in the array.

  5. #5
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: Reuse same Scanner to read another file

    In fact reset() is true to label and "discards all of its explicit state information". So not just radix, but locale and delimeter pattern are zapped.

    Don't use reset() unless you really mean that to happen. If the Scanner instance reads (or might be reading) a file, then a case could be made for calling close() when you've finished reading the file as this is designed to release any system resources that might be being used. (Your program shares these resources with other things going on on the computer, so it's polite to free them as soon as possible.)

    In general the wisdom is that "object creation is cheap". But when people say that they are talking about zillions of objects (and then they make exceptions in the case of creating mega-zillions). In your case the cost of creating one or two new objects is a few nanoseconds and a few bytes at most. Moreover when we think about the time cost, it's the slowest part of the operation that counts. Compared with computation, reading a file from disk is s-l-o-w. And reading user typed information from the console is unbelievably slow. So the few nanoseconds you might save on object creation is swamped by the millions of nanoseconds it takes the user to figure out where they put the "J" on the keyboard.

    ns.reset();
    x = 0;
    ns = Scanner(new File(file2)); // should be ns = new Scanner(new File(file2));

    Notice that this code *does* create a new scanner (if corrected). It's just the variable ns that is reused. A brand new scanner is created, so the previous call to reset() resets a completely different scanner and, from your program's point of view, that does nothing at all.

    Be careful where you declare variables. ns is declared in a try block and will only be visible within that block. This is true for any Java variable: if you declare a variable it goes out of scope and becomes "invisible" once you hit the } ending the block where it was declared.

  6. The Following User Says Thank You to pbrockway2 For This Useful Post:

    KevinWorkman (April 1st, 2013)

  7. #6
    Junior Member
    Join Date
    Apr 2013
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Reuse same Scanner to read another file

    Thought reset() would allow the scanner to start reading the file again from start. Now know I know even less than I thought I did. I don't need the scanner visible outside the try block, only using it there to read the file and fill the array which has been originally declared outside the block. Just wanted to know if I can make the same scanner start reading the file again or do I need a new scanner (was leaving out the new as it already created).

  8. #7
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: Reuse same Scanner to read another file

    Thought reset() would allow the scanner to start reading the file again from start.
    No. It resets state like the what counts as delimiter between the ints (which you are not using). But it doesn't affect the position of the scanner within the stream. So if you reset() then keep reading you will be reading from where you left off (-1 or end of file) not from the start of the file.

    By far the easiest way to start reading the file again is to create a new Scanner.

    The use of the name "reset" for this functionality could be a little bit confusing because if you reset() a BufferedReader it really does go back to the start. This means that you *can* reuse a Scanner instance if you really, really want to. But, I repeat, it is much easier not to.

    To illustrate this I put a file containing "1 2 3 4 5 5 4 3 2 -1 1" in c:\temp\temp.txt and ran the following code:

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Scanner;
     
    public class ScannerTest {
        public static void main(String[] args) throws IOException {
            test1();
            test2();
        }
     
        static void test1() throws FileNotFoundException {
            Scanner in = new Scanner(new File("c:/temp/temp.txt"));
     
            int count = 0;
            while(in.hasNextInt() && in.nextInt() != -1) {
                count++;
            }
            System.out.println(count + " ints found");
     
            in.reset();
            System.out.println(in.nextLine());
     
            in.close();
        }
     
        static void test2() throws IOException {
            BufferedReader br = new BufferedReader(new FileReader("c:/temp/temp.txt"));
            br.mark(100000); // <-- mark the start of the underlying reader
            Scanner in = new Scanner(br);
     
            int count = 0;
            while(in.hasNextInt() && in.nextInt() != -1) {
                count++;
            }
            System.out.println(count + " ints found");
     
            br.reset(); // <-- reset the underlying reader, not the scanner
            System.out.println(in.nextLine());
     
            in.close();
        }
     
    }

    The output is

    9 ints found
     1
    9 ints found
     11 2 3 4 5 5 4 3 2 -1 1

    The first two lines output show how resetting the Scanner had no effect on its position. The second two show that calling reset() on the underlying BufferedReader allowed content from the beginning to be read again. (although you get a junk character already buffered by the reader).

    I don't need the scanner visible outside the try block
    My mistake, I see that now the code is formatted.

Similar Threads

  1. Using for loop to read in data from text file using Scanner class
    By Scippi in forum Loops & Control Statements
    Replies: 23
    Last Post: February 26th, 2013, 10:53 PM
  2. Replies: 1
    Last Post: January 16th, 2013, 08:55 AM
  3. Can scanner read the specified line?
    By ice in forum File I/O & Other I/O Streams
    Replies: 7
    Last Post: January 28th, 2011, 09:35 AM
  4. Reading a file line by line using the Scanner class
    By JavaPF in forum File Input/Output Tutorials
    Replies: 0
    Last Post: April 17th, 2009, 07:34 AM
  5. Reading a file line by line using the Scanner class
    By JavaPF in forum Java Code Snippets and Tutorials
    Replies: 0
    Last Post: April 17th, 2009, 07:34 AM