我有一大堆大整数需要保存到磁盘以供下一个用户会话使用。我没有数据库或使用它的选项。 当我将它们写入文本文件时,大数字会在内存中占用更多空间吗? 存储此数组以供以后使用的最佳方法是什么?
答案 0 :(得分:0)
我只是使用普通的文本文件来获取它,整数将占用与其字符串表示一样多的空间,因此作为一个大整数的2759275918572192759185721将采用与2759275918572192759185721相同的空格作为字符串(这不是那个多)。
从文件中读取它们时,您只需再次解析它们。
重要提示:此代码中没有错误处理!你绝对必须将try-catch-finally添加到ctahc IOException和NumberformatException中!
File file = new File("C:\\Users\\Phiwa\\Desktop\\test.txt");
if(!file.exists())
file.createNewFile();
FileWriter fw = new FileWriter(file);
BigInteger bint1 = new BigInteger("999999999999999999");
fw.write(bint1.toString());
fw.flush();
fw.close();
// BigInteger has been written to file
// Read it from file again
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String str = br.readLine();
br.close();
BigInteger bint2 = BigInteger.valueOf(Long.parseLong(str));
System.out.println(bint2);
这个有效,你有没试过?
如果您的格式为0x999999999999999,那么情况会有所不同,在这种情况下您会使用
BigInteger bint2 = new BigInteger(str.replace("0x", ""), 16);