0

Is there any way I can reuse the Scanner object to read the same file again.

There is RandomAccessFile class that provides random access (seek) but I am looking for some code that uses Scanner. I know how to go to the stating position of the file by creating a new Scanner object, but the code looks messy.

Is there a neat and short method to do the same. Thanks in advance:-)

Also could you suggest good source/tutorial for learning file handling :p

Here is what I am trying to do:

Container.java

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Formatter;
import java.util.Scanner;

public class Container {
    private Scanner sc;
    private Formatter f;

    void openFile() throws FileNotFoundException{
            sc=new Scanner(new File("source"));
    }

    void readData(){
            while(sc.hasNext()){
                    System.out.println(sc.next());
            }
    }
    void readlineData(){
            while(sc.hasNextLine()){
                    System.out.println(sc.nextLine());
            }
    }

    void closeFile(){
            sc.close();
    }

    void addData() throws FileNotFoundException{
            f=new Formatter("source");
            f.format("%s%s", "hi "," hello");
    }
}

Client.java

import java.io.FileNotFoundException;

public class Client {

    public static void main(String[] args) throws FileNotFoundException {
            Container c=new Container();
            try {
                    c.openFile();
            } catch (FileNotFoundException e) {
                    System.out.println("No file with this name");
            }
            //reading word by word
            c.readData();//there is content already in the file
            //reading line by line
            c.readlineData();
            //changing the content of the file
            c.addData();
            //reading the file again
            c.readData();
        //closing the file
            c.closeFile();
    }
}

Here i have made a client and a container class. In the container class i have methods to create a file,read file word by word ,read line by liine and close file. In the client class i have called these methods .

MLavoie
  • 9,671
  • 41
  • 36
  • 56
user13245465
  • 3
  • 1
  • 2
  • Is [this answer](http://stackoverflow.com/a/3064422/824425) something you can work with? –  Jul 31 '16 at 14:01
  • Possible duplicate of http://stackoverflow.com/questions/34822927/how-to-reset-scanner – totoro Jul 31 '16 at 14:01

0 Answers0