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();
System.out.println("File created: "+bool);
}catch(Exception e){
e.printStackTrace();
}
}
}
让我们编译和运行上面的程序,这将产生以下结果:
File created: false
delete() method is invoked
File created: true