aspose file tools*
The moose likes Beginning Java and the fly likes Confusion with using scanner to read a file over multiple functions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Confusion with using scanner to read a file over multiple functions" Watch "Confusion with using scanner to read a file over multiple functions" New topic
Author

Confusion with using scanner to read a file over multiple functions

Johna Smith
Greenhorn

Joined: Feb 12, 2012
Posts: 2
Hi all,

I have a java assignment that I can't seem to wrap my mind around. There is one part right now that I'm struggling with.

The instuctions ask for 2 functions + main , one that will take a string and when called and will open the string as a file if it exists. I should catch the FilNotFoundException and print the message inside this function.Just to make it clearer...

public void openSF(String file){...}

Inside main function I should call the 2nd function in a loop to read each line of the file. The 2nd function will take a string again as a parameter which will be the file name.

public int readAndprocess(String fileName) {...}

I got the openSF function to open the file but inside main I need to somehow loop calling readAndprocess function multiple times. I thought, ok no problem I'll do the following loop...

Scanner scanner = new Scanner("Input.txt");

while(scanner.hasNextLine())
{asm.readAndprocess("Input.txt");}

For testing purposes I just want the 2nd function to output the next line of the file to the screen so I know whats going on, like this..

public void readAndprocess(String file) {
Scanner lineScanner = new Scanner(file);
String lineText = lineScanner.next();
System.out.println (lineText);
}

I currently just get Input.txt spamming forever.
Perhaps I'm missing something with scanners or maybe there is another option. Any help would be appreciated.
Rik Roos
Greenhorn

Joined: Feb 06, 2012
Posts: 13
Your second function constructs a new Scanner object. This seems not something you really want.
I think you are better off by passing the reference of the main-scanner object to the 2nd function.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36453
    
  15
And welcome to the Ranch
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Confusion with using scanner to read a file over multiple functions
 
Similar Threads
Hey guys, A little help with binary trees
Trouble with '.hasNext() '
Reading and converting only one line to String and storing it in an array
Creating a new file using PrintWriter.
ERROR - "system cannot find the file specified"