java判断文件不存在就创建的方法

内容摘要
1、判断文件是否存在,不存在创建文件File file=new File("C:UsersQPINGDesktopJavaScript2.htm");
if(!file.exists())
{
try {
file.createNew
文章正文

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

1
2
3
4
5
6
7
8
9
10
File file=new File("C:UsersQPINGDesktopJavaScript2.htm");   
if(!file.exists())   
{   
    try {   
        file.createNewFile();   
    } catch (IOException e) {   
        // TODO Auto-generated catch block   
        e.printStackTrace();   
    }   
}

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

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

1
2
3
4
5
6
7
8
9
10
File file =new File("C:UsersQPINGDesktopJavaScript");   
//如果文件夹不存在则创建   
if  (!file .exists()  && !file .isDirectory())     
{      
    System.out.println("//不存在"); 
    file .mkdir();   
} else  
    System.out.println("//目录存在"); 
}

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

代码注释
[!--zhushi--]

作者:喵哥笔记

IDC笔记

学的不仅是技术,更是梦想!