1 Replies - 3254 Views - Last Post: 20 June 2008 - 03:25 AM Rate Topic: -----

#1 amir_ju  Icon User is offline

  • D.I.C Head

Reputation: 17
  • View blog
  • Posts: 82
  • Joined: 20-June 08

I can't use FileWriter!

Posted 20 June 2008 - 03:07 AM

class Main {
	public static void main(String args[]) {
		FileWriter w = null;
		
		try {
			w = new FileWriter("test.txt");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		w.write("Hello world!");
	}
}


I wrote this code in default package. 'test.txt' is created, but nothing is written to the file.
Is This A Good Question/Topic? 0
  • +

Replies To: I can't use FileWriter!

#2 mihir83in  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 13
  • Joined: 04-June 08

Re: I can't use FileWriter!

Posted 20 June 2008 - 03:25 AM

Here is corrected code
import java.io.FileWriter;
import java.io.IOException;
class Main {
	public static void main(String args[]) {
		FileWriter w = null;
	try{
		w = new FileWriter("test.txt");
		w.write("Hello world!");
		w.close();
	}catch(IOException e) {e.printStackTrace();}
	
	}
}




You have to import the FileWriter and IOException classes before using them , you can do that in single statement too

import java.io.*;

And you placed w.write("Hello World"); outside the try catch block, it should be inside as it can too generate an IOException,

Thirdly , you should close a stream before exiting, you should close the test.txt, by w.close(); and it also throws an IOException so it should also be put inside the try catch block.

Hope that helps you,
Regards,
Mihir Pandya

This post has been edited by mihir83in: 20 June 2008 - 03:27 AM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1