Java-mkdir()不写目录 [英] Java - mkdir() not writing directory

查看:233
本文介绍了Java-mkdir()不写目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是代码:

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)

推荐答案

可能是因为File.mkdir仅在父目录存在的情况下才创建目录. 尝试使用 File.mkdirs 创建所有必要的目录.

It's possibly because File.mkdir creates the directory only if the parent directory exists. Try using File.mkdirs which creates all the necessary directories.

这是对我有用的代码.

Here's the code which 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();
    }
}

我所做的唯一更改是将f.mkdir()更改为f.mkdirs(),并且有效

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

这篇关于Java-mkdir()不写目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆