Java 创建文件

创建文件

要在 Java 中创建文件,可以使用 createNewFile() 方法。此方法返回一个布尔值:如果成功创建文件,则返回 true;如果文件已存在,则返回 false

请注意,该方法应该包含在 try…catch 块中,这是必要的,因为如果发生错误(如果由于某种原因无法创建文件),它可以引发 IOException:

实例
  1. import java.io.File; // Import the File class
  2. import java.io.IOException; // Import the IOException class to handle errors
  3. public class CreateFile {
  4. public static void main(String[] args) {
  5. try {
  6. File myObj = new File("filename.txt");
  7. if (myObj.createNewFile()) {
  8. System.out.println("File created: " + myObj.getName());
  9. } else {
  10. System.out.println("File already exists.");
  11. }
  12. } catch (IOException e) {
  13. System.out.println("An error occurred.");
  14. e.printStackTrace();
  15. }
  16. }
  17. }

输出将为:

File created: filename.txt

要在特定目录中创建文件(需要权限),请指定文件路径,并使用双反斜杠转义 "\" 字符(对于 Windows)。在 Mac 和 Linux 上,您只需编写路径,如:/Users/name/filename.txt

实例
  1. import java.io.File;
  2. import java.io.IOException;
  3. public class CreateFileDir {
  4. public static void main(String[] args) {
  5. try {
  6. File myObj = new File("C:\\Users\\MyName\\filename.txt");
  7. if (myObj.createNewFile()) {
  8. System.out.println("File created: " + myObj.getName());
  9. System.out.println("Absolute path: " + myObj.getAbsolutePath());
  10. } else {
  11. System.out.println("File already exists.");
  12. }
  13. } catch (IOException e) {
  14. System.out.println("An error occurred.");
  15. e.printStackTrace();
  16. }
  17. }
  18. }

分类导航