Search code examples
javabigintegerobjectinputstream

Turning an InputStream into BigInteger


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?


Solution

  • 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));