gpt4 book ai didi

Java:创建文件或目录(如果不存在)

转载 作者:太空宇宙 更新时间:2023-11-04 12:09:35 24 4
gpt4 key购买 nike

我的类获取一个包含路径 (dir1/dir2/abc.txt) 或文件 (def.txt) 的字符串,我想写入/读取该文件。如果该文件不存在,我想创建目录(如果有)和文件。

到目前为止我的类构造函数(“pfad”是一个实例变量):

public SerializedFahrzeugDAO(String path) {
pfad=path;

try{


FileInputStream filein= new FileInputStream(pfad);
ObjectInputStream in = new ObjectInputStream(filein);
List<Fahrzeug> liste = (List<Fahrzeug>)in.readObject();
in.close();
FileOutputStream fileout = new FileOutputStream(pfad);
ObjectOutputStream out = new ObjectOutputStream(fileout);

out.writeObject(liste);
out.close();

}
catch (Exception f){
if(f instanceof FileNotFoundException){
try{
File ziel = new File(pfad);
File dir= new File(ziel.getParentFile().getAbsolutePath());
dir.mkdirs();
FileOutputStream fileout = new FileOutputStream(pfad);
ObjectOutputStream out = new ObjectOutputStream(fileout);
List<Fahrzeug> newlist = new ArrayList<Fahrzeug>();
out.writeObject(newlist);
out.close();
}
catch(Exception y){System.out.println(y); }
}

else {System.out.println(f);}}

它可以很好地处理“dir/file.txt”这样的路径,但如果我只输入文件名,我会得到一个NullPointerException

最佳答案

如果没有堆栈跟踪,我会假设异常发生在这里:

            File dir= new File(ziel.getParentFile().getAbsolutePath());

ziel 没有父级,因此 ziel.getParentFile()null

您可以先转换为绝对路径,然后获取父路径。

<小时/>

编辑(1):

您应该改进错误处理。

        catch(Exception y){System.out.println(y); }

不打印堆栈跟踪。您应该使用y.printStackTrace()(或适当的日志框架)。

<小时/>

编辑(2):

您应该使用 java.io.File 方法检查文件是否存在,而不是捕获 FileNotFoundException

关于Java:创建文件或目录(如果不存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39975615/

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