Java - mkdir () does not write directory

I am trying to create a directory, but it seems to fail every time? I checked that this is also not a permission problem, I have full permission to write to this directory. Thanks in advance.

Here is the code:

private void writeTextFile(String v){ try{ String yearString = convertInteger(yearInt); String monthString = convertInteger(month); String fileName = refernce.getText(); File fileDir = new File("C:\\Program Files\\Sure Important\\Report Cards\\" + yearString + "\\" + monthString); File filePath = new File(fileDir + "\\"+ fileName + ".txt"); writeDir(fileDir); // Create file FileWriter fstream = new FileWriter(filePath); try (BufferedWriter out = new BufferedWriter(fstream)) { out.write(v); } }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } } private void writeDir(File f){ try{ if(f.mkdir()) { System.out.println("Directory Created"); } else { System.out.println("Directory is not created"); } } catch(Exception e){ e.printStackTrace(); } } public static String convertInteger(int i) { return Integer.toString(i); } Calendar cal = new GregorianCalendar(); public int month = cal.get(Calendar.MONTH); public int yearInt = cal.get(Calendar.YEAR); 

Here is the result:

 Directory is not created Error: C:\Program Files\Sure Important\Report Cards\2012\7\4532.txt (The system cannot find the path specified) 
+7
source share
2 answers

Perhaps because File.mkdir only creates a directory if a parent directory exists. Try using File.mkdirs , which creates all the necessary directories.

Here is the code that worked for me.

 private void writeDir(File f){ try{ if(f.mkdirs()) { System.out.println("Directory Created"); } else { System.out.println("Directory is not created"); } } catch(Exception e){ // Demo purposes only. Do NOT do this in real code. EVER. // It squashes exceptions ... e.printStackTrace(); } } 

The only change I made was to change f.mkdir() to f.mkdirs() and it worked

+24
source

I think that @La bla bla nailed it, but just for completeness, thatโ€™s all I can think of about it, it can call File.mkdir() :

  • Syntax error in transit; e.g. illegal character in file name component
  • A directory containing the final component of the directory does not exist.
  • There is already something with this name.
  • You do not have permission to create a directory in the parent directory
  • You do not have permission to search in some directory on the way
  • The directory you create is located in the read-only file system.
  • The file system provided a hardware error or a network-related error.

(Obviously, some of these possibilities can be quickly eliminated in the context of this question ...)

+6
source

All Articles