Create a directory if it does not exist and then create the files in that directory as well

前端 未结 7 1250
礼貌的吻别
礼貌的吻别 2020-12-12 14:36

Condition is if directory exists it has to create files in that specific directory with out creating a new directory.

The below code only creating a file with new di

7条回答
  •  猫巷女王i
    2020-12-12 15:03

    If you create a web based application, the better solution is to check the directory exists or not then create the file if not exist. If exists, recreate again.

        private File createFile(String path, String fileName) throws IOException {
           ClassLoader classLoader = getClass().getClassLoader();
           File file = new File(classLoader.getResource(".").getFile() + path + fileName);
    
           // Lets create the directory
           try {
              file.getParentFile().mkdir();
           } catch (Exception err){
               System.out.println("ERROR (Directory Create)" + err.getMessage());
           }
    
           // Lets create the file if we have credential
           try {
               file.createNewFile();
           } catch (Exception err){
               System.out.println("ERROR (File Create)" + err.getMessage());
           }
           return  file;
       }
    

提交回复
热议问题