Fork me on GitHub

Java判断文件、文件夹是否存在

  在完成工作室任务的时候多次遇到这个问题,这是一个常用的知识点,记录如下:

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

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

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

File file =new File("C:\\images");    
//如果文件夹不存在则创建    
if  (!file .exists()  && !file .isDirectory())      
{       
    System.out.println("//不存在");  
    file .mkdir();    
} else   
{  
    System.out.println("//目录存在");  
} 
posted @ 2015-06-28 18:57  何海洋  阅读(3199)  评论(0编辑  收藏  举报