
1、判断文件是否存在,不存在创建文件
1 2 3 4 5 6 7 8 9 10 | File file= new File( "C:\\Users\\QPING\\Desktop\\JavaScript\\2.htm" );
if (!file.exists())
{
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
|
ログイン後にコピー
2、判断文件夹是否存在,不存在创建文件夹
1 2 3 4 5 6 7 8 9 10 | File file = new File( "C:\\Users\\QPING\\Desktop\\JavaScript" );
if (!file .exists() && !file .isDirectory())
{
System.out.println( "//不存在" );
file . mkdir ();
} else
{
System.out.println( "//目录存在" );
}
|
ログイン後にコピー
备注:文件路径是filePath = D:\word\111\test.txt 带文件的,使用getParentFile 获取父文件
1 2 3 | if (!file.getParentFile().isDirectory()){
file.getParentFile().mkdirs();
}
|
ログイン後にコピー
推荐教程:java快速入门
以上がJavaにファイルまたはフォルダーが存在するかどうかを確認するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。