如何使用ObjectOutput和Input Stream

时间:2013-11-14 02:19:02

标签: java file-io fileinputstream fileoutputstream

我正在做家庭作业,我差不多完成了它。这里的最后一部分是创建一个文件,从该文件读取然后内容用于执行一些计算。根据API和一些网站,我看到我的语法是正确的但由于某种原因它没有按预期执行。任何帮助引导我朝正确方向的帮助将不胜感激。我收到了读写错误的错误。

try{
        //In the space below (between Marker 2 and Marker 3) declare an 
        //ObjectOutputStream object called "outFile" for the purpose of 
        //writing Fraction objects into a file called "fraction.out"

        //Marker 2

         FileOutputStream fos = new FileOutputStream("fraction.out");
         ObjectOutputStream outFile = new ObjectOutputStream(fos);


        //Marker 3

        score += 5;

        outFile.writeObject(F[1]);
        outFile.writeObject(F[2]);
        outFile.writeObject(F[3]);
        outFile.close();
    }
    catch(Exception e){
        System.out.println("Could not write objects to file");
    }


    try{
        //In the space below (between Marker 4 and Marker 5) declare an 
        //ObjectInputStream object called "inFile" for the purpose of 
        //reading Fraction objects from a file called "fraction.out"

        //Marker 4

        ObjectInputStream inFile =
                 new ObjectInputStream(new FileInputStream("fraction.out"));


        //Marker 5

        score += 5;


        //In the space below (between Marker 6 and Marker 7) Complete
        //statements that read three fraction objects from the file 
        //as F[5], F[6], and F[7]

        //Marker 6

        f[5] = (Fraction) inFile.readObject();
        f[6] = (Fraction) inFile.readObject();
        f[7] = (Fraction) inFile.readObject();


        //Marker 7
        inFile.close();

        F[4] = F[5].multiply(F[6]).multiply(F[7]);
        score += 5;
        System.out.println("step 12:\tf4 = " + F[4]);
    }
    catch (Exception e){
        System.out.println("Could not read objects from file");

    }

2 个答案:

答案 0 :(得分:0)

readObject()的返回值是从流中读取的对象。你把它扔掉了。

答案 1 :(得分:-1)

当我最终打印堆栈跟踪时,我注意到它是一个可序列化的错误。一旦我在标题中修复了它就可以了。