Home  >  Article  >  Java  >  Java method to determine if a file does not exist and then create it

Java method to determine if a file does not exist and then create it

尚
Original
2019-12-14 10:07:248482browse

Java method to determine if a file does not exist and then create it

1、判断文件是否存在,不存在创建文件

File file=new File("C:\\Users\\QPING\\Desktop\\JavaScript\\2.htm");    
if(!file.exists())    
{    
    try {    
        file.createNewFile();    
    } catch (IOException e) {    
        // TODO Auto-generated catch block    
        e.printStackTrace();    
    }    
}

File 的 createNewFile() 方法:        createNewFile();返回值为 boolean; 方法介绍:当且仅当不存在具有此抽象路径名指定名称的文件时,不可分地创建一个新的空文件。

2、判断文件夹是否存在,不存在创建文件夹

File file =new File("C:\\Users\\QPING\\Desktop\\JavaScript");    
//如果文件夹不存在则创建    
if  (!file .exists()  && !file .isDirectory())      
{       
    System.out.println("//不存在");  
    file .mkdir();    
} else   
{  
    System.out.println("//目录存在");  
}

更多java知识请关注java基础教程栏目。

The above is the detailed content of Java method to determine if a file does not exist and then create it. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn