将InputStream转换为BigInteger

时间:2017-05-17 02:03:39

标签: java biginteger objectinputstream

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();
      }

   }

这是我学习如何使用Input / OutputStream的程序。除了在尝试将文件转换为BigInteger时出现错误,一切正常 java.lang.String无法强制转换为java.math.BigInteger     在ReadOutPutStream.main
   我是新手,所以我可能犯了一个简单的错误,我做错了什么?

1 个答案:

答案 0 :(得分:1)

您使用

在文件中写了一个字符串
Vector3Wrap

因此,当您从流中读取对象时,它也将是oout.writeObject(Line); 。您无法将String转换为String,因此您会收到例外情况。我知道你要在序列化BigInteger之前形成你之前的问题以节省从文件系统反序列化的时间,所以为了解决你的具体问题,你应该在流中写一个BigInteger而不是字符串:< / p>

BigInteger