gpt4 book ai didi

Java - mkdir() 不写目录

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:27:39 25 4
gpt4 key购买 nike

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

代码如下:

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这会创建所有必要的目录。

这是对我有用的代码。

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() 并且它起作用了

关于Java - mkdir() 不写目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12126987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com