gpt4 book ai didi

java - 为什么这段代码不创建文件?

转载 作者:行者123 更新时间:2023-12-02 03:26:46 24 4
gpt4 key购买 nike

我正在尝试使用这些方法创建文件:

private boolean createFileMain(String path){
File file = new File(path);
if(file.isDirectory()){
return this.createDirectory(file);
} else if(file.isFile()) {
return this.createFile(file);
} else {
return false;
}
}

private boolean createFile(File file){
if(!file.exists()){
if(file.getParentFile().exists()){
try{
if(file.createNewFile()){
return true;
}
}catch(IOException e){
return false;
}
} else {
if(this.createDirectory(file)){
this.createFile(file);
} else {
return false;
}
}
}
return true;
}

private boolean createDirectory(File file){
if(!file.exists()){
if(file.mkdirs()){
return true;
}
return false;
}
return true;
}

文件路径:

/Users/username/Directory/Accounts/

/Users/username/Directory/Srcs/file1.txt

/Users/username/Directory/file2.txt

当我尝试运行此方法时,以下方法会抛出 StackOverFlowError

public void writeInFile(String path, List<String> content) {
if ((new File(path)).exists()) {
try {
writer = new PrintWriter(path, "ASCII");
for (String contentItem : content) {
writer.println(contentItem);
}
writer.close();
} catch (FileNotFoundException e1) {
//DO STUFF
} catch (UnsupportedEncodingException e) {
//DO STUFF
}
} else {
this.createFileMain(path);
this.writeInFile(path, content);
}

为什么没有创建任何文件?

最佳答案

您阅读过有关 isDirectory() 等的 JavaDocs 吗?对于 isDirectory() 它说:

returns true if and only if the file denoted by this abstract pathname exists and is a directory; false otherwise

因此,如果该目录不存在,则会返回 false 并且不会创建该目录。然后你继续尝试写入、创建、写入等等,直到出现 StackOverFlowError。

要修复堆栈溢出,您应该检查创建文件的返回值,例如

boolean created = this.createFileMain(path);
if( created ) {
this.writeInFile(path, content);
}

要修复文件/目录创建问题,您需要检查文件是否已存在,否则创建它(也可以通过 file.getParentFile().mkdirs() 创建父目录)。

问题是您应该知道是否要创建文件或目录,因为您无法仅通过名称来判断路径是目录还是文件名(除非您发明了一些标记,例如始终以分隔符结束目录路径或要求文件始终具有扩展名)。如果您想编写一些内容,无论如何都需要创建一个文件,目录会再次破坏您的代码。

关于java - 为什么这段代码不创建文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38740586/

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