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}
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}