Home > Java > JavaBase > body text

How to determine whether a file exists in java and create a new file if it does not exist

王林
Release: 2019-11-25 10:10:55
Original
5920 people have browsed it

How to determine whether a file exists in java and create a new file if it does not exist

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

File file = new File("d:\\test.txt");
if (!file.exists()) {
    try {
        file.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("文件已创建");
} else {
    System.out.println("文件已存在");
}
Copy after login

相关学习视频推荐:java视频教程

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

File folder = new File("d:\\test1\\test2");
if (!folder.exists() && !folder.isDirectory()) {
    folder.mkdirs();
    System.out.println("创建文件夹");
} else {
    System.out.println("文件夹已存在");
}
Copy after login

推荐教程:java快速入门

The above is the detailed content of How to determine whether a file exists in java and create a new file if it does not exist. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!