bytes Files.write (path, content.getBytes (StandardCharsets.UTF_8)); The Files.write also accepts an Iterable interface; it means this API can write a List to a file">
Java Tutorials
Java Methods
Java Classes
Java File Handling
To create a file in Java, you can use the createNewFile()
method. This method returns the boolean value: true
if the file was successfully created, and false
if the file already exists. Note that the path is locked in the try ... catch
block. This is necessary because it throws IOException
in case of error (if the file could not be created for some reason):
import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to handle errors
public class CreateFile {
public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
The output will be:
File created: filename.txt
To create a file in a specific directory (requires permission), specify a file path and use duplicate backslash to escape the "\
" character (for Windows). For Mac and Linux you can simply write the path, such as: /Users/name/filename.txt
File myObj = new File("C:\\Users\\MyName\\filename.txt");
In the following example, we use the FileWriter
class and its write()
to write a specific text in a file we created in the example above. Note that when you have finished writing the file, you must close it with a close()
method:
import java.io.FileWriter; // Import the FileWriter class
import java.io.IOException; // Import the IOException class to handle errors
public class WriteToFile {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
The output will be:
Successfully wrote to the file.