English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this instance, we will learn to create a file using Java and write some information into the file.
To understand this example, you should understand the followingJava programmingTopic:
// Importing the File class import java.io.File; class Main { public static void main(String[] args) { //Create a file object for the current location File file = new File("JavaFile.java"); try { //Create a new file with the specified name //Through the file object boolean value = file.createNewFile(); if (value) { System.out.println("Create a new Java file."); } else { System.out.println("The file already exists."); } } catch(Exception e) { e.getStackTrace(); } } }
In the above example, we created a file object named file. The file object is linked to the specified path.
// JavaFile.java is equivalent to // currentdirectory/JavaFile.java File file = new File("JavaFile.java");
Then, we use the createNewFile() method of the File class to create a new file pointing to the specified path.
Note: If the file JavaFile.java does not exist, a new file will be created. Otherwise, the program returnsThe file already exists.
In Java, we can use the FileWriter class to write data to a file. In the previous example, we created a file named JavaFile.java. Now let's write the program into the file.
// Importing the FileWriter class import java.io.FileWriter; class Main { public static void main(String args[]) { //Using+An operator creates a multi-line string //A string is a Java program String program = "class JavaFile {" + "public static void main(String[] args) { " + "System.out.println("This is file");"+ ""+ "" try { //Create a Writer using FileWriter FileWriter output = new FileWriter("JavaFile.java"); //Write the program to the file output.write(program); System.out.println("Data written to file."); //Close the writer output.close(); } catch (Exception e) { e.getStackTrace(); } } }
In the above example, we used the FileWriter class to write string data to the file Javafile.java.
When you run the program, the file JavaFile.java will contain the data existing in the program.