Java創建文件的方法有以下幾種:
示例代碼:
File file = new File("path/to/file.txt");
try {
boolean success = file.createNewFile();
if (success) {
System.out.println("文件創建成功");
} else {
System.out.println("文件已存在");
}
} catch (IOException e) {
e.printStackTrace();
}
示例代碼:
String content = "Hello, World!";
byte[] bytes = content.getBytes();
try {
FileOutputStream fos = new FileOutputStream("path/to/file.txt");
fos.write(bytes);
fos.close();
System.out.println("文件創建成功");
} catch (IOException e) {
e.printStackTrace();
}
示例代碼:
String content = "Hello, World!";
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("path/to/file.txt"));
writer.write(content);
writer.close();
System.out.println("文件創建成功");
} catch (IOException e) {
e.printStackTrace();
}
這些方法可以根據具體的需求選擇適合的方法來創建文件。