Java File to Binary Conversion

后端 未结 3 795
半阙折子戏
半阙折子戏 2020-12-10 09:20

How can i convert File to Binary? I just need it for my project. I need to encrypt a file by its binaries.

3条回答
  •  一整个雨季
    2020-12-10 09:47

    If you're referring to accessing the ACTUAL BINARY form then read in the file and convert every byte to a binary representation...

    EDIT:

    Here's some code to convert a byte into a string with the 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're referring to accessing the bytes in the file then simply use the following code (you can use this for the first case as well):

    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 over every byte and create a String object (8X larger than the original file size!!) with the bits:

    String content = "";
    for(byte b : fileData)
        content += getBits(b);
    // content now contains your bits.
    

提交回复
热议问题