java - 将输入流转换为 BigInteger

标签 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
我是新手,所以我可能犯了一个简单的错误,我做错了什么?

最佳答案

您使用

将字符串写入文件
oout.writeObject(Line);

因此,当您从流中读取对象时,它也将是一个String。您无法将 String 转换为 BigInteger,因此会出现异常。从您之前的问题中我知道您希望序列化 BigInteger 以节省从文件系统反序列化时的时间,因此要解决您的特定问题,您应该将 BigInteger 写入流而不是字符串:

oout.writeObject(new BigInteger(Line));

关于java - 将输入流转换为 BigInteger,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44014317/

相关文章:

java - 用Camel读取文件中的对象?

java - 在 Eclipse 中激活项目资源管理器的快捷键

c++ - 将字符串中的 bigint 除以 2

java - 如何使用Java读取CSV中第 'x'行和第 'y'列的值?

java - 如何使用 BigInteger 将二进制转换为十进制?

algorithm - 一种计算任意大整数的整数平方根 (isqrt) 的有效算法

java - 将用户首选项保存/加载到文件

java - 将java流切换为密码流

java - 房间数据库观察者

java - Spring Security 和 JSF,找不到资源/j_spring_security_check.jsp