gpt4 book ai didi

java - 无论操作系统如何创建文件和文件夹

转载 作者:行者123 更新时间:2023-11-30 06:14:03 25 4
gpt4 key购买 nike

我写了一个程序,下面是它的一部分。当我在我的电脑上运行它时,它工作得很好。但是当我将此复制到我 friend 的 PC 时,它在第四行显示 FileNotFoundException

String d = System.getProperty("user.home");
String dir = d + "\\Documents\\CarPark";
new File(dir + "\\abnormal").mkdir();
PrintWriter restoreNo = new PrintWriter(new FileOutputStream(dir + "\\abnormal\\restoreNo.txt"));

谁知道问题出在哪里?谢谢!

最佳答案

将 mkdir 更改为 mkdirs。对于其他操作系统,使用 File.separator 而不是 '\'

String d = System.getProperty("user.home");
String dir = d + File.separator+"Documents"+File.separator+"CarPark";
final File file = new File(dir, "abnormal");
file.mkdirs();// all directories down
PrintWriter restoreNo = new PrintWriter(new FileOutputStream(new File(file, "restoreNo.txt"));

文件分隔符:

The system-dependent default name-separator character, represented as a string for convenience. This string contains a single character, namely separatorChar.

创建目录:

Creates the directory named by this abstract pathname.

mkdirs,来自 JavaDoc:

Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.

关于java - 无论操作系统如何创建文件和文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31031073/

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