In this tutorial you will learn how to write file using java
Java File Writing Example
To Write a file in Java, at first create a File reference variable and pass its references to FileWriter class as.
File file = new File("D:\\test-file.txt"); FileWriter fileWriter = new FileWriter(file, true);
Here true indicates that the file will append. If we make it false then
Make a PrintWriter reference variable by passing the FileWriter references to its constructor and call the print() method to write data to a file and finally close the objects.
PrintWriter printWriter = new PrintWriter(fileWriter); printWriter.println("Write Something to File"); fileWriter.close();
The Following is an example to write data to a file
JavaFileWritingExample.java
import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; public class JavaFileWritingExample { public static void main(String[] args) { try { File file = new File("D:\\test-file.txt"); FileWriter fileWriter = new FileWriter(file, true); PrintWriter printWriter = new PrintWriter(fileWriter); printWriter.println("Write Something to File"); fileWriter.close(); } catch (Exception e) { e.printStackTrace(); } } }
[ 0 ] Comments