0
public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    // Load file with 17 million digit long number
    BufferedReader Br = new BufferedReader (new FileReader("test2.txt"));
    String Line = Br.readLine();

      try {

         // create a new file with an ObjectOutputStream
         FileOutputStream out = new FileOutputStream("test.txt");
         ObjectOutputStream oout = new ObjectOutputStream(out);

         // write the number into a new file
         oout.writeObject(Line);

         // close the stream
         oout.close();

         // create an ObjectInputStream for the new file
         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt"));

         // convert new file into a BigInteger
         BigInteger Big = (BigInteger) ois.readObject();


      } catch (Exception ex) {
         ex.printStackTrace();
      }

   }

This is a program I made for learning how to use Input/OutputStream. Everything works except that I get an error when trying to turn my file into a BigInteger.
java.lang.String cannot be cast to java.math.BigInteger at ReadOutPutStream.main
I'm new to this so I'm probably making a simple error, what am I doing wrong?

Samantha Clark
  • 201
  • 2
  • 9

1 Answers1

1

You wrote a string to the file with

oout.writeObject(Line);

Therefore when you read an object from the stream it will also be a String. You can't cast a String to a BigInteger so you get an exception. I know form your earlier question that you want to serialize the BigInteger to save time when deserializing from the filesystem, so to fix your specific problem you should write a BigInteger to the stream instead of a string:

oout.writeObject(new BigInteger(Line));
Samuel
  • 16,923
  • 6
  • 62
  • 75
  • Oh, I had no idea that affected it. The whole reason I was doing this is that the string is so long it takes about an hour for it to be converted into a BigInteger. Hopefully this'll be the last time I have to wait, fingers crossed – Samantha Clark May 17 '17 at 02:10
  • I saw your other question. Good luck! Hopefully reading the binary version is a lot faster. – Samuel May 17 '17 at 02:13
  • Thank you for the help, I hope so too since the number is only going to get larger from here – Samantha Clark May 17 '17 at 02:15
  • Important lesson: `ObjectInputStream` only reads back the exact objects that were stored in the file by an `ObjectOutputStream`; you can't convert what you originally wrote to a different type while reading it back! – Kevin Anderson May 17 '17 at 02:23