java mkdir 权限,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.

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 output:

Directory is not created

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

解决方案

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

}

}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值