Skip to main content

Writing to a file

3 replies [Last post]
ajaymenon_k
Offline
Joined: 2007-11-15
Points: 0

I am very new to java 5 .As a learning thing, i was writing some sample code on
using scanner utilities to scan a file and see the output.

After scanning, i tried writing the output to a file like this :

File file = new File("E:///xanadu.txt");
try {
scanner = new Scanner(file);
pw = new PrintWriter(new FileWriter("E:///scanneroutput.txt"));
while (scanner.hasNextLine()) {
String l = scanner.nextLine();
//System.out.println(l);
pw.print(l);
}

} catch (Exception e) {

} finally {

System.out.println("Out File Generated.");
if (scanner != null) {
scanner.close();
}
}

But the output is not getting written to the file.But when i use S.O.P it is getting printed on the screen. I couldnt understand why this is happening ? Can anybody please help me out ?

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
jmelvin
Offline
Joined: 2004-12-01
Points: 0

After closer inspection, it looks like you are not closing the PrintWriter instance.
Try adding a pw.close() after your while() loop, and the stream should be flushed.

- Jim

jmelvin
Offline
Joined: 2004-12-01
Points: 0

Hmmm... The 'Quick Starter' program helps to start *java* faster, rather than new Java developers. :)

However, I think you might want to check for exceptions in your program.
Your code currently ignores any issues handling scanneroutput.txt. Try
inserting an 'e.printStackTrace();' after your 'catch' line. Perhaps that will
provide more clues. Perhaps you have too many slashes.

- Jim

ajaymenon_k
Offline
Joined: 2007-11-15
Points: 0

Jim -
I will keep that in mind :)

Regarding the problem, it is not spitting out any exceptions.It is creating the file.
But it is not just writing the output to the file.

Also, the "///" is working fine when i am reading from one file and copying from another file.