To create a new file and write text on it. We can write to a file using Java in different ways but I show you how to write text to a file using BufferedWriter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package classOneGeneral;
 
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
 
public class WriteToFile {
 
public static void main(String[] args) throws IOException {
 
String textToWrite = “I am learning Java from SoftwareTestingMaterial”;
// Import BufferedWriter and FileWriter classes
/* BufferedWriter writes text to a character-output stream, buffering characters
so as to provide for the efficient writing of single characters, arrays, and strings. */
//Import FileWriter and BufferedWriter class
BufferedWriter writer = new BufferedWriter(new FileWriter(“D:\\WriteToFile.txt”));
writer.write(textToWrite);
    // Close the BufferedWriter object to prevent memory leak
writer.close();
}
}

Must Read: Java Tutorial