java中createNewFile怎么使用?

2025-06-23 07:01:24
推荐回答(3个)
回答1:

java中createNewFile方法主要是如果该文件已经存在,则不创建,返回一个false,如果没有,则返回true,如下代码:

package com.yiibai;

import java.io.File;

public class FileDemo {
   public static void main(String[] args) {
      
      File f = null;
      boolean bool = false;
      
      try{
         // create new file
         f = new File("test.txt");//在默认路径创建一个file类
         
         // tries to create new file in the system
         bool = f.createNewFile();//返回true或者false判断该文件是否已经创建好
         
         // prints
         System.out.println("File created: "+bool);
         
         // deletes file from the system
         f.delete();
         
         // delete() is invoked
         System.out.println("delete() method is invoked");
         
         // tries to create new file in the system
         bool = f.createNewFile();
         
         // print
         System.out.println("File created: "+bool);
            
      }catch(Exception e){
         e.printStackTrace();
      }
   }
}
让我们编译和运行上面的程序,这将产生以下结果:
File created: false
delete() method is invoked
File created: true

回答2:

如果创建的文件名不存在,再创建

回答3:

File file=new File("1.txt");
if(!file.exists())
file.createNewFile();