zoukankan      html  css  js  c++  java
  • Java 当文件不存在时自动创建文件目录和文件

    操作文件流的时候,经常遇到在新目录中创建文件的场景,因此,这里记录如何判断文件是否存在,如果不存在,则如何创建目录和文件。

        public static void main(String[] args) {
            // 可以是任意格式的文件
            String pathName = "D:\img\test2.txt";
            createFile(new File(pathName));
           
        }
    
    
    
        /**
         * 判断文件是否存在,不存在就创建
         * @param file
         */
        public static void createFile(File file) {
            if (file.exists()) {
                System.out.println("File exists");
            } else {
                System.out.println("File not exists, create it ...");
                //getParentFile() 获取上级目录(包含文件名时无法直接创建目录的)
                if (!file.getParentFile().exists()) {
                    System.out.println("not exists");
                    //创建上级目录
                    file.getParentFile().mkdirs();
                }
                try {
                    //在上级目录里创建文件
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    

      读后有收获,小礼物走一走,请作者喝咖啡。

    赞赏支持

  • 相关阅读:
    Apache HTTP Server 与 Tomcat 的三种连接方式介绍(转)
    Java实现二叉树遍历以及常用算法
    随想-经验
    Java代码检查工具
    MongoDB学习笔记-维护
    脏检查
    html5对密码加密
    JavaSript模块化-AMD规范与CMD规范
    AngularJS的$watch用法
    常用的几个小函数
  • 原文地址:https://www.cnblogs.com/east7/p/15456848.html
Copyright © 2011-2022 走看看