Java - 无法将对象作为文件写入目录

时间:2016-06-07 15:49:12

标签: java file object io directory

我的程序有一个奇怪的问题。 我写了一个小程序来将对象写入特定目录中的文件。

播放器级:

package readwrite;

import java.io.Serializable;

public class Player implements Serializable {

    private String name;
    private int level;

    public Player(String name, int level) {
        this.name = name;
        this.level = level;
    }

    public String getName() {
        return name;
    }

    public int getLevel() {
        return level;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setLevel(int level) {
        this.level = level;
    }

    public String toString() {
        return "Name: " + name + ", Level: " + level;
    }

    public void printInfo() {
        System.out.println(this.toString());
    }

}

PlayerReaderWriter级:

package readwrite;

import java.io.*;

public class PlayerReaderWriter {

    public static Player readPlayer(String path) {
        Player p = null;

        try {
            FileInputStream fileIn = new FileInputStream(path);
            ObjectInputStream in = new ObjectInputStream(fileIn);
            p = (Player) in.readObject();
            in.close();
            fileIn.close();
        } catch(IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        return p;
    }

    public static void writePlayer(String path, Player p) {
        try {
            File file = new File(path);
            if (file.exists()) {
                file.delete();
                file.createNewFile();
            } else {
                file.mkdirs();
                file.createNewFile();
            }

            FileOutputStream fileOut = new FileOutputStream(path);
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(p);
            out.close();
            fileOut.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Player p = new Player("Foo", 64);
        p.printInfo();
        writePlayer("players/Player.ser", p);

        Player q = readPlayer("players/Player.ser");
        q.printInfo();
    }

}

问题是:当我第一次运行我的程序时,当目录"播放器"不存在,我收到以下错误:

D:\Projects>java readwrite/PlayerReaderWriter
Name: Foo, Level: 64
java.io.FileNotFoundException: players\Player.ser (Access is denied)
        at java.io.FileOutputStream.open0(Native Method)
        at java.io.FileOutputStream.open(FileOutputStream.java:270)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
        at readwrite.PlayerReaderWriter.writePlayer(PlayerReaderWriter.java:34)
        at readwrite.PlayerReaderWriter.main(PlayerReaderWriter.java:47)
java.io.FileNotFoundException: players\Player.ser (Access is deniedt)
        at java.io.FileInputStream.open0(Native Method)
        at java.io.FileInputStream.open(FileInputStream.java:195)
        at java.io.FileInputStream.<init>(FileInputStream.java:138)
        at java.io.FileInputStream.<init>(FileInputStream.java:93)
        at readwrite.PlayerReaderWriter.readPlayer(PlayerReaderWriter.java:11)
        at readwrite.PlayerReaderWriter.main(PlayerReaderWriter.java:49)
Exception in thread "main" java.lang.NullPointerException
        at readwrite.PlayerReaderWriter.main(PlayerReaderWriter.java:50)

现在目录&#34;玩家&#34;由程序创建,由于某种原因,它还创建了一个名为&#34; Player.ser&#34;的子目录

当我第二次运行它时,它可以工作并创建一个&#34; Player.ser&#34; 文件在&#34;玩家&#34; 。目录

当我用一个名为&#34的空目录运行它时,玩家&#34;它也不会工作。

问候:)

2 个答案:

答案 0 :(得分:5)

看看这段代码:

if (file.exists()) {
    file.delete();
    file.createNewFile();
} else {
    file.mkdirs();
    file.createNewFile();
}

您说如果players/Player.ser不存在,您应该将其创建为作为目录 - 然后再将其作为文件创建。那已经坏了。

如果文件已经存在,您根本不需要删除该文件 - 您可以使用FileOutputStream并覆盖该文件,将其截断为开头,这是默认行为。

您只需要先检查目录是否存在,例如

File file = new File(path);
File parent = file.getParentFile();
// TODO: Handle parent existing, but not being a directory,
// or file existing, but being a directory...
if (!parent.exists()) {
    parent.mkdirs();
}

try (OutputStream output = new FileOutputStream(file)) {
    // ...
}

请注意try-with-resources语句,以便即使抛出异常,输出流也始终关闭。

答案 1 :(得分:0)

查看File#mkdirs()上的JavaDoc:

  

创建由抽象路径名...

命名的目录

这表示假定文件代表一个目录,因此Player.ser被创建为目录。请改用file.getParentFile().mkdirs()(请记住,根据路径可能没有父级)。

由于您的代码正在创建目录,因此对该File对象的任何写操作都将失败,因为您无法将数据直接写入目录。