1import java.io.FileWriter; // Import the FileWriter class
2import java.io.IOException; // Import the IOException class to handle errors
3
4public class WriteToFile {
5 public static void main(String[] args) {
6 try {
7 FileWriter myWriter = new FileWriter("filename.txt");
8 myWriter.write("Files in Java might be tricky, but it is fun enough!");
9 myWriter.close();
10 System.out.println("Successfully wrote to the file.");
11 } catch (IOException e) {
12 System.out.println("An error occurred.");
13 e.printStackTrace();
14 }
15 }
16}
1// example on createNewFile() method of File class in java
2import java.io.File;
3import java.io.IOException;
4public class CreateFileDemo
5{
6 public static void main(String[] args) throws IOException
7 {
8 try
9 {
10 File file = new File("D:\\demo.txt");
11 boolean bool = file.createNewFile();
12 if(bool)
13 {
14 System.out.println("File created successfully");
15 }
16 else
17 {
18 System.out.println("File already exists");
19 }
20 }
21 catch(IOException ex)
22 {
23 System.out.println("Exception : ");
24 ex.printStackTrace();
25 }
26 }
27}
1File myObj = new File("path");
2myObj.createNewFile();
3FileWriter myWriter = new FileWriter("path");
4myWriter.write("text");
5myWriter.close();
1String fileData = "yourContent";
2FileOutputStream fos = new FileOutputStream("yourFile.txt");
3fos.write(fileData.getBytes());
4fos.flush();
5fos.close();
1package FileHandling;
2
3 // Import the File class
4import java.io.File;
5
6// Import the IOException class to handle errors
7import java.io.IOException;
8
9public class CreateFile {
10public static void main(String[] args) {
11try {
12// Creating an object of a file
13File myObj = new File("D:FileHandlingNewFilef1.txt");
14if (myObj.createNewFile()) {
15System.out.println("File created: " + myObj.getName());
16} else {
17System.out.println("File already exists.");
18}
19} catch (IOException e) {
20System.out.println("An error occurred.");
21e.printStackTrace();
22}
23}
24}