I need to do this project where I take a binary file read from it, and then make a new binary file that has adds 00 depending on the offset. So for example, if the binary number is at offset 02, it will shift that binary number by 2. So that binary number will be at 04. with 00 in between.
I am thinking of using the Random Access File to access it and edit (read only). But I am lost at by how many bytes do you seek. Also, how do edit and put the modification into a brand new file.
Kindest Regards
In the image above. the first byte in blue (0x54)
is at 0x40 + 0x0E
. Add the left row value plus the column value. So you must read everthing up to but excluding that byte. So that would be offset 0x40 + 0x0D
. That would be 64 + 13 = 77
. Since the offset starts at 0
, read in the first 78
bytes then write out what you want. Then write out the rest of the file. That means all the blue would be written after you special insertion.
This is all presuming that, that is what you want to do. But you can't really use seek
because that would imply you are modifying the source file which is not wise (since you might make a mistake and need to start over). Also seeking into a file under modification can be very problematic since its size may keep changing. In any event make certain you keep a backup copy of the file.
To make further modifications, keep reading and writing as described.
Here is a brute force example. It could be improved with try-with-resources and loops as appropriate. Exceptions are presumed to be monitored. This example simply inserts two triads of integers in specified locations and them prints the new file.
// create a file to start
FileOutputStream fo = new FileOutputStream("myfile.txt");
String alpha = "abcdefghijklmnopqrstuvwxyz";
fo.write(alpha.getBytes());
fo.close();
// create the new output file and open up the old one as an input
// file
fo = new FileOutputStream("myfile2.txt");
FileInputStream fi = new FileInputStream("myfile.txt");
// insert 123 after k
byte[] buf = new byte[100];
int count = fi.read(buf, 0, 11); // read up to and including k
fo.write(buf, 0, count);
fo.write("123".getBytes());
// insert 456 after t
count = fi.read(buf, 0, 9);
fo.write(buf, 0, count);
fo.write("456".getBytes());
//copy rest of input file to output file
while ((count = fi.read(buf, 0, 10)) > 0) {
fo.write(buf, 0, count);
}
fo.close();
fi.close();
fi = new FileInputStream("myfile2.txt");
byte[] buffer = fi.readAllBytes();
for (byte b : buffer) {
System.out.print((char) b);
}
System.out.println();
fi.close();
}