Java - mkdir()不写目录

Nic*_*ick 8 java mkdir

我正在尝试创建一个目录,但它似乎每次都失败了?我已经检查过它也不是权限问题,我有完全权限写入该目录.提前致谢.

这是代码:

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);
Run Code Online (Sandbox Code Playgroud)

这是输出:

Directory is not created
Error: C:\Program Files\Sure Important\Report Cards\2012\7\4532.txt (The system cannot find the path specified)
Run Code Online (Sandbox Code Playgroud)

La *_*bla 25

这可能是因为File.mkdir仅当父目录存在时才创建目录.尝试使用File.mkdirs它创建所有必要的目录.

这是适合我的代码.

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

我所做的唯一改变是改变f.mkdir()f.mkdirs()和它的工作


Ste*_*n C 6

我认为@La bla bla已经确定了它,但为了完整性,以下是我能想到的所有可能导致调用File.mkdir()失败的事情:

  • 路径名中的语法错误; 例如,文件名组件中的非法字符
  • 包含最终目录组件的目录不存在.
  • 已经有了这个名字的东西.
  • 您无权在父目录中创建目录
  • 您无权在路径上的某个目录中执行查找
  • 要创建的目录位于只读文件系统上.
  • 文件系统出现硬件错误或网络相关错误.

(显然,在这个问题的背景下,可以迅速消除其中一些可能性......)