Reputation: 835
I'm having a problem with my scanner object. It seems like if I pass the scanner into a static method, the scanner isn't able to read the file it was given in the main function. When I pass the file object into scanner, and then pass scanner into the Add function it does not output the file contents to the console. However, if I comment out the scanner part of the Add function, the scanner will read just fine. This has led me to believe that the scanner is able to see the file, but not read from it. My question is how do I read from the file a second time, this time within the Add function?
public static void main(String[] args) throws IOException
{
File file = new File("vinceandphil.txt");
if (file.createNewFile())
{
System.out.println("New file was created");
}
else {
System.out.println("File already exists");
}
Scanner sc = new Scanner(file);
FileWriter writer = new FileWriter(file);
writer.write("Test data\n");
Add(file, writer, sc);
writer.close();
while (sc.hasNextLine())
{
System.out.println(sc.nextLine());
}
sc.close();
}
public static void Add(File f, FileWriter w, Scanner scanner) throws IOException
{
if (f.exists())
{
w.write("Got em coach\n");
w.write("We need more info\n");
w.write("Come again\n");
}
while (scanner.hasNextLine())
{
System.out.println(scanner.nextLine());
}
}
Upvotes: 1
Views: 200
Reputation: 21134
You cannot do that. Once a line has been read via nextLine()
, it gets "thrown away", and the pointer goes to the next one.
To start again from the beginning of the file, you have to instantiate another Scanner
.
final Scanner yourNewScanner = new Scanner(file);
If you want a way to move around your file, look into RandomAccessFile
.
You're pointing out your Scanner
doesn't print out anything.
That's because you haven't closed the file stream before asking the Scanner
to read.
if (f.exists())
{
w.write("Got em coach\n");
w.write("We need more info\n");
w.write("Come again\n");
// Adding this call flushes and closes the data stream.
w.close();
}
Upvotes: 2