将 InputStream 转换为 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();
      }

   }

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

塞缪尔

你写了一个字符串到文件中

oout.writeObject(Line);

因此,当您从流中读取对象时,它也将是String. 你不能将 a 转换String为 aBigInteger所以你会得到一个例外。我从您之前的问题中知道您想要序列化BigInteger以节省从文件系统反序列化时的时间,因此要解决您的特定问题,您应该将 a 写入BigInteger流而不是字符串:

oout.writeObject(new BigInteger(Line));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章