5

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

James P.
  • 19,313
  • 27
  • 97
  • 155
Ran Gualberto
  • 714
  • 5
  • 15
  • 22

4 Answers4

17

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.
1

Simple explanatory code to encode / decode :

To Encode:

// Encode Character | char
Integer.toBinaryString(myByte);
// Encode Byte | byte
Integer.toBinaryString(myCharacter);

To decode :

// Use BigInteger insted of Integer beacause it can decode large binary code(2)
new BigInteger(data, 2).toByteArray()

Encode file :

private static void encodeToBinary(File inputPath, File outputPath) throws IOException {

        // Read all the bytes from the input file

        InputStream inputData = new FileInputStream(inputPath);
        ByteArrayOutputStream fileData = new ByteArrayOutputStream();
        inputData.transferTo(fileData);

        // StringJoiner to store binary code(2) encoded

        StringJoiner binaryData = new StringJoiner(" ");

        // Convert every byte into binaryString

        for(Byte data : fileData.toByteArray()) {
            binaryData.add(Integer.toBinaryString(data));
        }

        // (File)OutputStream for writing binary code(2)

        OutputStream outputData = new FileOutputStream(outputPath);
        outputData.write(binaryData.toString().getBytes());

        // [IMPORTANT] Close all the streams

        fileData.close();
        outputData.close();
        inputData.close();
    }

Decode file :

private static void decodeToFile(File inputPath, File outputPath) throws IOException {
        // -->>Just reverse the process

        // Read all the bytes from the input (binary code(2)) file to string

        InputStream inputData = new FileInputStream(inputPath);
        ByteArrayOutputStream fileData = new ByteArrayOutputStream();
        inputData.transferTo(fileData);

        // ByteArrayOutputStream to store bytes decoded

        ByteArrayOutputStream originalBytes = new ByteArrayOutputStream();

        // Convert every binary code(2) to original byte(s)

        for(String data : new String(fileData.toByteArray()).split(" ")) {
            originalBytes.write(new BigInteger(data, 2).toByteArray());
        }

        // (File)OutputStream for writing decoded bytes

        OutputStream outputData = new FileOutputStream(outputPath);
        outputData.write(originalBytes.toByteArray());

        // [IMPORTANT] Close all the streams

        inputData.close();
        fileData.close();
        originalBytes.close();
        outputData.close();
    }
Xoma Devs
  • 35
  • 1
  • 7
  • You can't use `Integer.toBinaryString` as its output is of variable length (broken really), so you wouldn't know how to decode it – g00se Dec 22 '22 at 23:51
1
        try {
            StringBuilder sb = new StringBuilder();
            File file = new File("C:/log.txt");
            DataInputStream input = new DataInputStream( new FileInputStream( file ) );
            try {
                while( true ) {
                    sb.append( Integer.toBinaryString( input.readByte() ) );
                }
            } catch( EOFException eof ) {
            } catch( IOException e ) {
                e.printStackTrace();
            }
            System.out.println(sb.toString());
        } catch( FileNotFoundException e2 ) {
            e2.printStackTrace();
        }
oliholz
  • 7,447
  • 2
  • 43
  • 82
0

With FileInputStream you can obtain the bytes from a File

From JavaDoc:

A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment.

FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.

oliholz
  • 7,447
  • 2
  • 43
  • 82
Charliemops
  • 749
  • 12
  • 30