Write to File
Write Content To File
If you want to write some data to a file, like names.txt
, contact.csv
. You can easily create new content to file or replace content to file. You can import java.io.FileWriter;
for writing data to file.
Create New File
import java.io.FileWriter; // need to import first.
public class Main{
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("myfile.txt");
myWriter.write("Wow, I wrote something on file.!");
myWriter.close();
System.out.println("Write to file successful.");
} catch (Exception e) {
System.out.println("Error "+e.getMessage());
}
}
}
Info
Note: This will write ‘Wow, I wrote something on file.!’ to myfile.txt. If there is an existing file, this process will delete all the content and add content.
Add New Content To Previous Content
If you want to add new content to previous content, you must set append mode to true and content. Here is an example of it.
import java.io.FileWriter; // need to import first.
public class Main{
public static void main(String[] args) {
try {
// Don't forget to add true here if you want to append.
FileWriter myWriter = new FileWriter("myfile.txt",true);
myWriter.write("Wow, I wrote something more on previous file.!");
myWriter.close();
System.out.println("Write to file successful.");
} catch (Exception e) {
System.out.println("Error "+e.getMessage());
}
}
}
Info
Note: This will write ‘Wow, I wrote something more on previous file.!’ to myfile.txt. If there is an existing file, this process will delete all the content and add content.