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

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

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("文件已存在");
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

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

File folder = new File("d:\\test1\\test2");
if (!folder.exists() && !folder.isDirectory()) {
    folder.mkdirs();
    System.out.println("创建文件夹");
} else {
    System.out.println("文件夹已存在");
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

作者:itmyhome

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

猜你喜欢

转载自www.cnblogs.com/skiwnchqhh/p/10339644.html
今日推荐