【问题标题】:FileOutputStream write binary file to a specified folderFileOutputStream 将二进制文件写入指定文件夹
【发布时间】:2013-08-22 11:05:32
【问题描述】:

我正在尝试将二进制文件写入指定文件夹,但它一直给我一个异常。 例如,如果我在不指定任何文件夹的情况下写入文件,程序将毫无问题地写入:

public void saveFile(String name) throws IOException {
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(name + ".bin"));
    out.writeObject(this);
    out.close();
}

但是,当我尝试指定文件夹时,程序不会写入文件:

public void saveFile(String name) throws IOException {
    File location = new File("/path/" + name + ".bin");
    FileOutputStream fos = new FileOutputStream(location);

    ObjectOutputStream out = new ObjectOutputStream(fos);
    out.writeObject(this);
    out.close();
    fos.close();
}

我尝试了几种不同的方法,但仍然没有解决方案。 有人知道我做错了什么吗?

【问题讨论】:

  • 写堆栈跟踪

标签: java serialization fileoutputstream


【解决方案1】:

检查你要写的类是不是Serializable

public class Foo implements java.io.Serializable{   

    //...

    public void write() throws IOException{
        ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("Test.bin"));
        os.writeObject(this);
        os.close();
    }   

}

另一个问题: 如果没有名为path 的文件夹,则无法写入对象

再次检查您的代码。

【讨论】:

  • 是的,它是可序列化的。您使用的方式是我可以做的方式,无需指定任何路径。这样我就可以毫无问题地做到这一点。
  • 检查是否有一个文件夹以你想要的名字命名。
  • 问题已解决。非常感谢,伙计:)我以为程序会自动创建路径,但似乎我错了。
【解决方案2】:

非序列化的唯一原因似乎是你可能没有实现 Serializable 接口 并正确给出您的路径名称,例如:-“C:\Users\..” 希望有效

【讨论】:

  • 问题是我输入了一个不存在的路径。我认为该程序会创建该路径,但它没有...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-26
  • 1970-01-01
  • 1970-01-01
  • 2017-06-30
  • 1970-01-01
相关资源
最近更新 更多