Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java I';我试图制作一个程序,将一个对象保存到文件中,然后从文件中读取该对象。我做错了什么?_Java_File_Save - Fatal编程技术网

Java I';我试图制作一个程序,将一个对象保存到文件中,然后从文件中读取该对象。我做错了什么?

Java I';我试图制作一个程序,将一个对象保存到文件中,然后从文件中读取该对象。我做错了什么?,java,file,save,Java,File,Save,我认为它保存对象是因为它生成了.txt文件,但当我运行程序时,在输入输入后,它会输出“错误初始化流”。我不熟悉Java和一般的编码,所以我只是想知道我做错了什么 下面是我运行代码时得到的结果: “你想要什么样的服装 大猩猩套装 你想要什么类型的面具 大猩猩“ 这是你的衣服 服装:大猩猩套装 面具:大猩猩 初始化流时出错“ 我希望对象(“gorilla套装”和“gorilla”)的内容 输出在最后一行,但它输出“初始化流时出错” 以下是跑步者课程: class RunHalloween2 {

我认为它保存对象是因为它生成了.txt文件,但当我运行程序时,在输入输入后,它会输出“错误初始化流”。我不熟悉Java和一般的编码,所以我只是想知道我做错了什么

下面是我运行代码时得到的结果:

“你想要什么样的服装

大猩猩套装

你想要什么类型的面具

大猩猩“

这是你的衣服

服装:大猩猩套装

面具:大猩猩

初始化流时出错“

我希望对象(“gorilla套装”和“gorilla”)的内容 输出在最后一行,但它输出“初始化流时出错”

以下是跑步者课程:

class RunHalloween2
{
   public static void main(String[] args)
   {
      Scanner Input = new Scanner(System.in);


      Halloween outfit = new Halloween();

      System.out.println("What type of costume do you want?");
      outfit.setCostume(Input.nextLine());

      System.out.println("What type of mask do you want?");
      outfit.setMask(Input.nextLine());

      System.out.println("");
      System.out.println("This is your outfit.");
      System.out.println("Costume: " + outfit.getCostume());
      System.out.println("Mask:    " + outfit.getMask());


        try {
            FileOutputStream f = new FileOutputStream(new File("myOutfit.txt"));
            ObjectOutputStream o = new ObjectOutputStream(f);

            // Write objects to file
            o.writeObject(outfit);

            o.close();
            f.close();

            FileInputStream fi = new FileInputStream(new File("myOutfit.txt"));
            ObjectInputStream oi = new ObjectInputStream(fi);

            // Read objects

            outfit = (Halloween) oi.readObject();


            System.out.println(outfit.toString());

            oi.close();
            fi.close();

        } catch (FileNotFoundException e) {
            System.out.println("File not found");
        } catch (IOException e) {
            System.out.println("Error initializing stream");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

据我所知,可能有2个错误:-

1-您的文件名是
myOutfit.txt
,但它应该是
myOutfit.ser

2-你的万圣节课没有实现系列化

public class Halloween implements java.io.Serializable

欢迎使用SO!发布您的代码是一个很好的开始,但到底是什么问题?您遇到了什么问题?您做了什么尝试并解决了它们?预期的结果是什么?您可以发布错误跟踪吗?您提供的信息越多,您获得有帮助的及时回复的机会就越高。