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/