Java Create File: Top Methods
There are several ways to create files in Java.
- Using the File class: you can create a File object by using the constructor of the File class, and then call its createNewFile() method to create a file.
File file = new File("example.txt");
file.createNewFile();
- By using the FileOutputStream class, you can create an output stream to write data into, ultimately creating a file.
FileOutputStream fos = new FileOutputStream("example.txt");
// 写入数据到文件
fos.write("Hello, world!".getBytes());
fos.close();
- By using the BufferedWriter class, you can create a writing stream to write data into the stream and ultimately create a file.
BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"));
writer.write("Hello, world!");
writer.close();
- Using the Files class: You can use the write() method of the Files class to create a file and write data to it.
String content = "Hello, world!";
Files.write(Paths.get("example.txt"), content.getBytes());
- Using the RandomAccessFile class: It is possible to create a random access file with the RandomAccessFile class and then write data to it.
RandomAccessFile raf = new RandomAccessFile("example.txt", "rw");
raf.writeBytes("Hello, world!");
raf.close();