I am writing a java program in which I have to write all integers to a file. To make it more efficient I just want to write int as only 4 bytes(which I think will be a binary file kind of thing, but I am not sure) and while reading back from the file I just want to read the integers directly(I do not want to read bytes and then convert them to integer). Is there a way to do that.
I want to write millions of integers to the file I want the method to be fast and efficient.
I am new to this so please put up with me.
The int and unsigned int types have a size of four bytes. However, portable code should not depend on the size of int because the language standard allows this to be implementation-specific.
The fact that an int uses a fixed number of bytes (such as 4) is a compiler/CPU efficiency and limitation, designed to make common integer operations fast and efficient.
Integers are commonly stored using a word of memory, which is 4 bytes or 32 bits, so integers from 0 up to 4,294,967,295 (232 - 1) can be stored.
The byteValue() method of Integer class of java. lang package converts the given Integer into a byte after a narrowing primitive conversion and returns it (value of integer object as a byte).
Use the DataOutputStream
class or a RandomAccessFile
. Both provide methods for writing structured binary data, for example the "int as 4 bytes" you want.
FileOutputStream fos = new FileOutputStream("numbers.dat");
DataOutputStream dos = new DataOutputStream(fos);
dos.writeInt(my_int);
dos.flush();
dos.close();
If you want to have the data buffered wrap the file stream in to a buffered stream as below:
FileOutputStream fos = new FileOutputStream("numbers.dat");
BufferedOutputStream bos = new BufferedOutputStream(fos);
dos = new DataOutputStream(bos);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With