5

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

6
  • 3
    Files are already binary data. Please give more information. Commented Aug 19, 2011 at 8:52
  • What do you mean by convert a File to binary exactly? Commented Aug 19, 2011 at 8:54
  • 1
    if you mean file to byte array: exampledepot.com/egs/java.io/file2bytearray.html Commented Aug 19, 2011 at 8:55
  • I need to make a program the can encrypt any types of file. Based on our proposal we are going to encrypt file by its binary. Commented Aug 19, 2011 at 8:57
  • 1
    Then see my post. It's what you want. Also discard any of the String stuff... It's now irrelevant. Commented Aug 19, 2011 at 9:00

4 Answers 4

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.
Sign up to request clarification or add additional context in comments.

1 Comment

Do you think I can reverse it. binary representation to file.
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();
        }

1 Comment

For xml just change to log.xml
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();
    }

1 Comment

You can't use Integer.toBinaryString as its output is of variable length (broken really), so you wouldn't know how to decode it
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.