I have a large array of big integers which I need to save to the disk for the next user session. I don't have a data base or the option to use one. Will large numbers take more space in memory when I write them to a text file? What is the best way to store this array for later use?
Asked
Active
Viewed 572 times
1 Answers
0
I'd just go for it using a normal text file, the integer will take as much space as its string representation, so 2759275918572192759185721 as a big integer will take the same space as 2759275918572192759185721 as a string (which isn't that much).
When reading them from the file, you simply parse them again.
IMPORTANT: There is NO error handling in this code! You abosolutely MUST add try-catch-finally to ctahc IOException and 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);
This works, did you already try this?
Things are a bit different if you have the integer in the format 0x999999999999999, in that case you would use
BigInteger bint2 = new BigInteger(str.replace("0x", ""), 16);

Phiwa
- 319
- 1
- 8
-
Wow thanks for the thorough response. Wouldn't it be better to convert the bigint to hexadecimal or even to a larger base to save storage if a number is like a string when saved to a text file? – Geremy Dec 06 '14 at 11:01
-
Sure, feel free to convert it and use a hex base (should be big enough). In that case you'd use my last line to read it back into memory, but that works for all bases even though I'd prefer hex. – Phiwa Dec 06 '14 at 11:06
-
So would you recommend Hex base as the best practice? Or is there a conversion that will be more efficient in terms of disk space? – Geremy Dec 06 '14 at 11:10
-
I would definitely recommend either decimal or (if you really want to save some bits of disk space) hex. Go ahead and try writing some millions of big ints to the text file, the file size shouldn't be worth mentioning. – Phiwa Dec 06 '14 at 11:13