How to write array of bytes to a binary file in Java - java

How to write an array of bytes b[i] to a binary file in Java.
I need to write those bytes it into a "binary file" to be able to read it later using hex editor (AXE).
Some readers might be confused by "binary file", by binary file I don't mean a file filled by zeros and ones, I mean machine-readable form, something like this :
binary files in text editor
The hex editor suppose to read this data, hex editor
From what I understand I need to byte stream that data into a file
Is there a command I could use for this purpose.
Any code would be appreciated.

Just write the byte[] to a FileOutputStream pointing to the file:
private static void writeBytesToFile(byte[] b, String f) {
try (FileOutputStream out = new FileOutputStream(f)){
out.write(b);
}
catch (IOException e) {
e.printStackTrace();
}
}

Related

what is the variable "data" storing in this java program?

My code is working. I just need to know about the role of a specific variable in the code.
I tried to print the value in the variable "data", but it gives me some numbers i cant understand.
public static void main(String[] args) throws IOException {
FileInputStream fileinputstream = new FileInputStream ("c:\\Users\\USER\\Desktop\\read.TXT");
FileOutputStream fileoutputstream = new FileOutputStream("c:\\Users\\USER\\Desktop\\write.TXT");
while (fileinputstream.available() > 0) {
int data = fileinputstream.read();
fileoutputstream.write(data);
}
fileinputstream.close();
fileoutputstream.close();
}
You can look at the docs for FileInputStream.read, which says:
Reads a byte of data from this input stream. This method blocks if no input is yet available.
Returns:
the next byte of data, or -1 if the end of the file is reached.
So the integer you got (i.e. the number stored in data) is the byte read from the file. Since your file is a text file, it is the ASCII value of the characters in that file (assuming your file is encoded in ASCII).
FileInputStream#read() reads a single byte of information from the underlying file.
Since these files are text files (according to their extensions), you probably should be using a FileInputStream, but a FileReader, to properly handle characters, and not the bytes that make them up.
fileinputstream.read() returns "the next byte of data, or -1 if the end of the file is reached."
You can read more here

Java write bytes from Bytebuffer to File in byte format

I'm building a custom file creater app with Android. I'm attempting to write the contents of a Bytebuffer, which are String members from a custom class I created, to a file in byte type. However, whenever I do so I get the contents of the file in String format. I've tried several alternatives such as using get method, BufferedOutputStream class, ByteArrayOutputStream class, DataOutputStream, Filechannel class, etc. Here is my code:
ByteBuffer byteBuffer = ByteBuffer.allocate(totalSize);
byteBuffer.put(hm.getDocID().getBytes());
byteBuffer.put(hm.getFextension().getBytes());
byteBuffer.put(hm.getMagic().getBytes());
byteBuffer.put(hm.getFversion().getBytes());
byteBuffer.put(hm.getFsize().getBytes());
byteBuffer.flip();
byte[] bablock = new byte[byteBuffer.remaining()];
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(idHeader));
bos.write(bablock);
bos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Keep getting the following contents on my idHeader file:
12345678-1234-1234-1234-123456789abcjpgIDF1.00000166178
Which is all of my Strings concatenated. What I would like to do is write the same contents as bytes to the file, not as a human-readable string. What I am missing here? Any help is appreciated.
So instead of building Strings and getting byte arrays from them and putting those to the ByteBuffer and writing that to the file, you need to write the data directly. I would get rid of the ByteBuffer and use the various APIs of DataOutputStream to write the individual bytes or ints or whatever.
It being entirely unclear whether you want to write 12345678 as 8 bytes or as a 4-byte integer, for example, it is impossible to help you further without clarification.

How to read binary file in to a 100 bytes length array

I want to read a binary file in to a byte array, not in to a single byte array
but in to a 100 bytes length array, maybe with a loop...
public void readBinaryFile()
{
byte data[] = null;
try {
Path path1 = Paths.get("image.jpg");
data = Files.readAllBytes(path1);
} catch (Exception e) {
System.out.println("file reading error!!!");
}
System.out.println("img length: "+data.length);
}
I use for such purposes my JBBP library which allows to parse binary file partially ad to read only header for instance, you can find some examples of usage in tests of the library

Insert boolean in RTF file using java

I have no idea how can I insert boolean sign into RTF document from java programm. I think about √ or ✓ and –. I tried insert these signs to clear document and save it as *.rtf and then open it in Notepad++ but there is a lot of codes (~160 lines) and I can not understand what is it. Do you have any idea?
After a short search I found this:
Writing unicode to rtf file
So a final code version would be:
public void writeToFile() {
String strJapanese = "日本語✓";
try {
FileOutputStream fos = new FileOutputStream("test.rtf");
Writer out = new OutputStreamWriter(fos, "UTF8");
out.write(strJapanese);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Please read about RTF
√ or ✓ and – are not available in every charset, so specify it. If yout output in UTF-8 (and i advise you to do so, check here on how to do this). You might need to encode the sign aswell, check Wikipedia

Where to start in building an app/system that compresses and decompresses a file

I'm currently developing an application in Java/Android that allows the user to compress and decompress files. At first, I started to study the file size such as:
1Byte = 8Bits
1KB = 1024Byte
1MB = 1024KB
1GB = 1024MB
1TB = 1024GB
1PB = 1024TB
1EB = 1024PB
1ZB = 1024EB
1YB = 1024ZB
After I studied this, I studied and read some articles on the net and found out there are 2 types of file compression (Correct me if I'm wrong): Lossless and Lossy. Lossless compression means that a file is compressed into a smaller bit without losing any single file while lossy compression means that important files were being removed while compressing the file.
I also read that compression(run-length coding method) is like this:
AAABBCCDFFFFEEEEH
to this:
3A2B2CD4F4EH
which gives me an idea on how compressing/decompressing works on file.
I also searched the net that there is an API for compressing file on java(also applicable on android) which is
java.util.zip
I also tried some codes on compressing and decompressing file from various helpful websites/forum/etc (including stackoverflow.com) which gives me an experience to this study.
I also read about algorithms used in data compression which are
Huffman encoding algorithm - assigns a code to characters in a file based on how frequently those characters occur
run-length encoding - generates a two-part value for repeated characters: the first part specifies the number of times the character is repeated, and the second part identifies the character
Lempel-Ziv algorithm - converts variable-length strings into fixed-length codes that consume less space than the original strings.
Now, I need to know how to code an algo in compressing and decompressing file by using java.util.zip(I also don't know how to use it. tutorials on net is not working for me :/). What algo does winzip, winrar, compressed folder(windows), and androzip(android app) is using? Will someone please teach me step by step(treat me as an unschooled person) on how java.util.zip works and the different algorithms. sorry for the long post folks. Thanks for the future help and posts(if there will be)!
public static final byte[] unzip(byte[] in) throws IOException {
// decompress using GZIPInputStream
ByteArrayOutputStream outStream =
new ByteArrayOutputStream(EXPECTED_COMPRESSION_RATIO * in.length);
GZIPInputStream inStream =
new GZIPInputStream ( new ByteArrayInputStream(in) );
byte[] buf = new byte[BUF_SIZE];
while (true) {
int size = inStream.read(buf);
if (size <= 0)
break;
outStream.write(buf, 0, size);
}
outStream.close();
return outStream.toByteArray();
}
public static final byte[] zip(byte[] in) {
try {
// compress using GZIPOutputStream
ByteArrayOutputStream byteOut=
new ByteArrayOutputStream(in.length / EXPECTED_COMPRESSION_RATIO);
GZIPOutputStream outStream= new GZIPOutputStream(byteOut);
try {
outStream.write(in);
} catch (Exception e) {
LOG.error("", e);
}
try {
outStream.close();
} catch (IOException e) {
LOG.error("", e);
}
return byteOut.toByteArray();
} catch (IOException e) {
LOG.error("", e);
return null;
}
}

Categories