-2

I have a method that is requiring me to serialize objects of a custom class 'Fraction'. When I attempt to save the object, I get a java.io.FileNotFoundException. What could I do to help alleviate the issue?

    public static void method3()  
    {
        //Serialize the Fraction class.  Save all the objects to a file named 
        //     <your name>Fractions.dat
        //replace <your name> with your name in the file name!
        //Be sure to close() the file after writing the data.

        Fraction[] fa =
        {
            new Fraction(35, 18), new Fraction(125, -30), new Fraction(-125, -30),
            new Fraction(0, 76), new Fraction(98, 12)
        };

        ArrayList<Fraction> alf = new ArrayList<Fraction>();
        alf.add(new Fraction(81, 9));
        alf.add(new Fraction(-75, 250));
        alf.add(new Fraction(2380, 754));
        
        
        //save all objects to the file here
        
        String fileName = "<your name>Fractions.dat";

        try {  
            ObjectOutputStream serializer = new ObjectOutputStream(new FileOutputStream(fileName));
            serializer.writeObject(fa); 
            serializer.writeObject(alf);
            serializer.close();
        } catch(FileNotFoundException e) {
            e.printStackTrace();
        } 
        catch (IOException e) {
            System.out.println("A problem occurred when serializing.");
            e.printStackTrace();
        }
       
    }

//I made sure to have the Fraction class implement Serializable as demonstrated below

import java.io.Serializable;

public class Fraction implements Comparable<Fraction>, Serializable
{
    

1 Answers1

0

You are using an invalid filename:

String fileName = "<your name>Fractions.dat";

that is not a valid name on basically any operating system. It is pretty obvious that you are supposed to replace <your name>.

f1sh
  • 11,489
  • 3
  • 25
  • 51