Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wrting integers as 4 bytes to file java

Tags:

java

file-io

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.

like image 894
Aman Deep Gautam Avatar asked Jun 04 '12 16:06

Aman Deep Gautam


People also ask

Is int always 4 bytes in Java?

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.

Why integer is 4 bytes in Java?

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.

How are 4 bytes int stored?

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.

Can we assign int to byte in Java?

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).


2 Answers

Use the DataOutputStream class or a RandomAccessFile. Both provide methods for writing structured binary data, for example the "int as 4 bytes" you want.

like image 84
Wormbo Avatar answered Sep 27 '22 01:09

Wormbo


 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);
like image 43
Suraj Chandran Avatar answered Sep 27 '22 01:09

Suraj Chandran