How to edit a .txt file in Java
-
26-09-2019 - |
Question
i think i can use "Scanner" to read a .txt file but how can i write or even create a new text file?
Solution
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.
OTHER TIPS
This Basic I/O and Files Tutorial should do the trick :)
Create a java.io.FileOutputStream to write it. To write text, you can create a PrintWriter
around it.
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!
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow