Print very large BigIntegers to a file in Java
I tried to print a very large BigInteger to an .txt file, but when the number reaches a certain size, it prints nothing. Code:
BigInteger bi = new BigInteger("16777216");
int exponent = 1000000;
bi = bi.pow(exponent);
String txtToPrint = bi.toString();
sendToFile(txtToPrint, "output.txt");
private static void sendToFile(String txtToPrint, String fileName) {
try {
FileWriter fileWriter = new FileWriter(fileName);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(txtToPrint);
bufferedWriter.close();
}
catch(IOException e) {
System.out.println("Error writing to file '" + fileName + "'");
}
}
Whenever the index is greater than 566, the output file is empty instead of containing numbers. The goal is to reach an index of 1,000,000 or even more.
I
don’t think BigInteger has a size limit, so my question is: what limit am I exceeding and is there a way around this?
EDIT: I get this exception when trying to refresh and close the file writer :
java.io.IOException: Stream closed
at sun.nio.cs.StreamEncoder.ensureOpen(Unknown Source)
at sun.nio.cs.StreamEncoder.flush(Unknown Source)
at java.io.OutputStreamWriter.flush(Unknown Source)
at PrintInt.main(PrintInt.java:4
EDIT: The problem only occurs when running the program in Eclipse, I tried exporting it to an external jar and everything works fine. I’m using Eclipse Mars.1 Release (4.5.1) and Java jre1.8.0_131 and CP1252 encoding.
Solution
I’m mostly guessing. I’m guessing the problem is with BufferWriter
.
Let’s try a more straightforward approach, Outputstream,
and try to properly close everything using resource.
File f = new File(fileName);
try (
FileOutputStream fos = new FileOutputStream(f);
OutputStreamWriter os = new OutputStreamWriter(fos);
Writer out = new BufferedWriter(os)
){
out.write(txtToPrint);
} catch(IOException e) {
System.out.println("Error writing to file '" + fileName + "'");
}
I’ve seen some OS sync issues in the past, but files never lose data, data is only copied with a small delay… But why not… After the write
, simply wait for the operating system to verify that the data has been flushed to a file (not in the operating system cache).
out.flush(); flush the stream
fos.getFD().sync(); sync with the OS