【问题标题】:Java - mkdir() not writing directoryJava - mkdir() 不写目录
【发布时间】:2012-08-21 01:20:42
【问题描述】:

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

代码如下:

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

这是输出:

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

【问题讨论】:

    标签: java mkdir


    【解决方案1】:

    这可能是因为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();
        }
    }
    

    我所做的唯一更改是将 f.mkdir() 更改为 f.mkdirs() 并且它起作用了

    【讨论】:

    • 干杯这似乎是问题所在,当它允许我接受时,我会接受答案:) 谢谢!!!
    • 由于路径名的“动态”部分有两个目录,我会说这个理论很好......
    • 我复制了您的代码,将其更改为 mkdirs() 并且它有效。编辑以包含相关代码
    【解决方案2】:

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

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

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

    【讨论】:

    • WINDOWS7 警告。我只是浪费了几个小时发现如果文件名包含任何目录部分,它是 Window7 遗留词之一(即:CON、PRN、AUX、CLOCK$、NUL、COM1-COM9、LPT1-LPT9 ......众所周知...不是吗?)然后 mkdirs 将在没有警告或明显逻辑解释的情况下失败。在 Java 7 b51 下找到 - 它可能不会影响其他版本的 Java 或其他编程语言。它不影响 DOS cmd shell。
    猜你喜欢
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 2015-04-06
    • 2021-12-16
    相关资源
    最近更新 更多