views:

129

answers:

4

i think i can use "Scanner" to read a .txt file but how can i write or even create a new text file?

+1  A: 

Create a java.io.FileOutputStream to write it. To write text, you can create a PrintWriter around it.

ZeissS
+3  A: 

This Basic I/O and Files Tutorial should do the trick :)

npinti
in this link it teaches about a class called 'Path' but its not in jdk 6 .and i'm not sure that jdk 7 is released.:?
masoud
A: 

To create a new text file

FileOutputStream object=new FileOutputStream("a.txt",true);
object.write(byte[]);
object.close();

This will create a file if not available and if a file is already available it will append data to it.

rgksugan
But that’s not very useful for writing *text*.
Konrad Rudolph
A: 

This simple code example will create the text file if it doesn't exist, and if it does, it will overwrite it:

try {
FileWriter outFile = new FileWriter("c:/myfile.txt");
PrintWriter out = new PrintWriter(outFile);
// Also could be written as follows on one line
// Printwriter out = new PrintWriter(new FileWriter(filename));
// Write text to file
out.println("This is some text I wrote");
out.close();
} catch (IOException e) {
e.printStackTrace();
}

Hope it helps!

ramayac