Writing long variables to file
The attach program works if I reduce the countLimit, but if it is above 10 trillion it gives me the following error: cannot find symbol
symbol : method write(long)
location: class java.io.FileOutputStream
output.write(number);
Code :
import java.io.*;
public class primenumbers {
public static void main(String[] args) throws IOException {
// Create an output stream to the file
FileOutputStream output = new FileOutputStream("Exercise23_7.dat");
long countLimit = 10000000000L;
long count = 0;
long number = 2;
while (count <= countLimit) {
// Assume the number is prime
boolean isPrime = true;
for (int divisor = 2; divisor <= number / 2; divisor++){
if (number % divisor == 0){
isPrime = false;
break;
}
}
if (isPrime){
//write prime number to a file
output.write(number);
System.out.println(number);
}
number++;
count++;
}
output.close();
FileInputStream input = new FileInputStream("Exercise23_7.dat");
int value;
while((value = input.read()) != -1)
System.out.print(value + " ");
input.close();
}
Re: Writing long variables to file
There is no write(long) method inside of FileOutputStream. Are you trying to write out the string representations of the number, or the actual value? Unicode only allows for 16-bit characters (some new "unicode" formats I think have 32-bits, don't quote me on this), so any value you try to write out that's greater than 0xFFFF will become truncated to 0xFFFF.
If you actually want to write out the string representation of the number, I would recommend using a PrintStream to wrap around your FileOutputStream.
If you do indeed want to write out the value 10000000000, you will need to split the number into 16-bit chunks (so you'll end up with 16 characters in total) and write out each chunk as it's own character (use bitwise and shift operators). There is an issue of endian-ness that you need to be careful of, though.