Java file to binary conversion

How to convert files to binary? I just need it for my project I need to encrypt the file through its binary file

Solution

If you mean accessing the actual binary table, read in the file and convert each byte into a binary representation

Edit:

Here are some codes to convert bytes into strings with bits:

String getBits(byte b)
{
    String result = "";
    for(int i = 0; i < 8; i++)
        result += (b & (1 << i)) == 0 ? "0" : "1";
    return result;
}

If you mean accessing the bytes in the file, just use the following code (you can also use it in the first case):

File file = new File("filename.bin");
byte[] fileData = new byte[file.length()];
FileInputStream in = new FileInputStream(file);
in.read(fileData):
in.close();
// Now fileData contains the bytes of the file

To use these two pieces of code, you can now loop through each byte and create a string object with bits (8 times larger than the original file size!!):

String content = "";
for(byte b : fileData)
    content += getBits(b);
// content Now contains your bits.
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>