Reputation: 366
i think i can use "Scanner" to read a .txt file but how can i write or even create a new text file?
Upvotes: 0
Views: 11980
Reputation: 5183
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!
Upvotes: 0
Reputation: 3582
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.
Upvotes: 0
Reputation: 12135
Create a java.io.FileOutputStream to write it. To write text, you can create a PrintWriter
around it.
Upvotes: 1