how to create a file using java code example
Example 1: writing to a file in java
import java.io.FileWriter;
import java.io.IOException;
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();
}
}
}
Example 2: Java create new file
import java.io.File;
import java.io.IOException;
public class CreateFileDemo
{
public static void main(String[] args) throws IOException
{
try
{
File file = new File("D:\\demo.txt");
boolean bool = file.createNewFile();
if(bool)
{
System.out.println("File created successfully");
}
else
{
System.out.println("File already exists");
}
}
catch(IOException ex)
{
System.out.println("Exception : ");
ex.printStackTrace();
}
}
}
Example 3: java create file
File filename = new File(filepath)