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();
            }
        }
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM