简体   繁体   English

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

[英]Java: Creating File or Directory if not existent

My class gets a String containing a Path (dir1/dir2/abc.txt) or a file (def.txt) and I want to write/read into that file. 我的类获取一个包含Path(dir1 / dir2 / abc.txt)或文件(def.txt)的String,我想写/读入该文件。 If the file does not exist I want to create the directories (if there are any) and the file. 如果文件不存在,我想创建目录(如果有的话)和文件。

My class constructor so far("pfad" is a instance-variable): 到目前为止我的类构造函数(“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);}}

It works fine with paths like "dir/file.txt", but if I only enter a filename I get a NullPointerException . 它适用于像“dir / file.txt”这样的路径,但是如果我只输入一个文件名,我会得到一个NullPointerException

Without having a stacktrace, I would assume, the exception happens here: 没有堆栈跟踪,我会假设,异常发生在这里:

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

ziel doesn't have a parent, so ziel.getParentFile() is null . ziel没有父级,因此ziel.getParentFile()null

You could first convert to absolute path then get the parent. 您可以先转换为绝对路径然后获取父路径。


Edit (1): 编辑(1):

You should improve your error handling. 您应该改进错误处理。

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

Doesn't print the stacktrace. 不打印堆栈跟踪。 You should use y.printStackTrace() instead (or a proper logging framework). 您应该使用y.printStackTrace()代替(或适当的日志框架)。


Edit (2): 编辑(2):

Instead of catching a FileNotFoundException , you should check if the file exists using a method of java.io.File . 您应该使用java.io.File方法检查文件是否存在,而不是捕获FileNotFoundException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM