I want to read binary file in java. I have 153(1.bin, 2.bin...153.bin) bin file. I must read that. I thought that I must use ArrayList for buffering. But I could not do that. How can I do this ?
After some research, I found that way in this title(Reading a binary input stream into a single byte array in Java). There is code like below in this title.
StringBuilder sb = new StringBuilder();
String fileName = "/path/10.bin";
byte[] buffer;
try {
buffer = Files.readAllBytes(Paths.get(fileName));
for(byte b : buffer){
sb.append(String.format("%02X ", b));
}
System.out.println(sb.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Is it true way for my question or do I must use Arraylist for buffering ? If I use single byte array for buffering, do I must clear the buffer for the other binary files.
Edit : 153 unit means 153 file(1.bin,2.bin ... 153.bin)
Your question is unclear. For one, you don't tell what those "units" are, how long they are etc. Second, all your code does is dump the contents of the file in hexadecimal.
What I suggest you do here is map the file into memory and use a class to wrap that around, and make it implement Closeable
.
See FileChannel.open()
and FileChannel.map()
. Please note however that it is unsafe to map more than 1 GiB in memory. This is not a "real" mmap()
.
I'm assuming a unit is one byte. Is this correct?
An ArrayList is not appropriate for byte buffering. It is a wrapper class for an array that implements the List interface (by which most of it's power is defined.)
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
If you simply want to read bytes in from a file, you could use FileInputStream.
http://docs.oracle.com/javase/tutorial/essential/io/bytestreams.html
Here's a simple example that reads input from a file containing "hello world!"
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Input {
public static void main(String[] args) throws FileNotFoundException, IOException {
try (FileInputStream in = new FileInputStream("test.txt")) {
int c;
while ( (c = in.read()) != -1 )
System.out.print((byte)c + " ");
}
}
}
Output in bytes: 104 101 108 108 111 32 119 111 114 108 100 33 13 10
I'm not sure what you mean by "units". Byte data is read something like that:
File f = new File ("File.txt");
FileInputStream fis = new FileInputStream (f);
byte[] bytes = new byte[(int) f.length ()];
fis.read (bytes, 0, (int) f.length () );
Make sure your File is not too big.