Results 1 to 3 of 3
  1. #1
    Nosrettap is offline Member
    Join Date
    Jan 2011
    Posts
    13
    Rep Power
    0

    Default Reset a Scanner to the beginning of a file

    How do I reset a scanner to the beginning of a file? If this is not possible can I make a copy of a scanner?

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

  3. #3
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    Quote Originally Posted by Fubarable View Post
    I think that you will need to create a new Scanner object.
    I agree completely.

    @OP - this is probably worth ignoring
    But, strangely, the following does ... something

    Java Code:
    import java.io.IOException;
    import java.io.StringReader;
    import java.util.Scanner;
    
    public class ScannerEg {
        public static void main(String[] args) throws IOException {
            String data = "This is a\nthree line\nimitation file";
    
            StringReader in = new StringReader(data);
            
            Scanner scanner = new Scanner(in);
            int counter = 1;
            
            //while(scanner.hasNext()) {
            //    System.out.printf("%d: %s%n", counter++, scanner.next());
            //}
            //System.out.printf("%d: %s%n", counter++, scanner.next());
            scanner.next();
            in.reset();
            while(scanner.hasNext()) {
                System.out.printf("%d: %s%n", counter++, scanner.next());
            }
        }
    }

    I think the scanner "reads ahead", so resetting the underlying stream will not do what you expect. It's no good skip()ping the unwanted input because once the scanner has seen the end of the stream hasNext() returns false even after the stream has been reset.

    StreamTokenizer, however, is a well behaved "wrapper" that respects the capacities of the underlying stream.
    Last edited by pbrockway2; 02-06-2011 at 03:39 AM.

Similar Threads

  1. Replies: 6
    Last Post: 01-15-2012, 04:01 AM
  2. Simple question Hopefully, Scanner/file
    By drucey in forum New To Java
    Replies: 23
    Last Post: 10-25-2010, 01:55 PM
  3. Replies: 9
    Last Post: 07-17-2010, 01:21 PM
  4. Beginning Programming with Java For Dummies
    By jon01 in forum New To Java
    Replies: 4
    Last Post: 02-16-2009, 08:40 PM
  5. Beginning Game Development - Suggestions?
    By JDCAce in forum Advanced Java
    Replies: 1
    Last Post: 12-08-2008, 05:42 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •