共計 933 個字符,預計需要花費 3 分鐘才能閱讀完成。
Java 創(chuàng)建文件的方法有以下幾種:
- 使用 File 類的 createNewFile() 方法:使用 File 類的 createNewFile() 方法可以創(chuàng)建一個新的文件。如果文件已存在,則返回 false,如果成功創(chuàng)建文件,則返回 true。
示例代碼:
File file = new File("path/to/file.txt");
try {boolean success = file.createNewFile();
if (success) {System.out.println(" 文件創(chuàng)建成功 ");
} else {System.out.println(" 文件已存在 ");
}
} catch (IOException e) {e.printStackTrace();
}
- 使用 FileOutputStream 類創(chuàng)建文件:使用 FileOutputStream 類可以創(chuàng)建一個新的文件,并可以向文件中寫入數(shù)據(jù)。
示例代碼:
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(" 文件創(chuàng)建成功 ");
} catch (IOException e) {e.printStackTrace();
}
- 使用 BufferedWriter 類創(chuàng)建文件:使用 BufferedWriter 類可以創(chuàng)建一個新的文件,并可以向文件中寫入數(shù)據(jù)。
示例代碼:
String content = "Hello, World!";
try {BufferedWriter writer = new BufferedWriter(new FileWriter("path/to/file.txt"));
writer.write(content);
writer.close();
System.out.println(" 文件創(chuàng)建成功 ");
} catch (IOException e) {e.printStackTrace();
}
這些方法可以根據(jù)具體的需求選擇適合的方法來創(chuàng)建文件。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完