Java File to Binary Conversion

后端 未结 3 796
半阙折子戏
半阙折子戏 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.
    
    0 讨论(0)
  • 2020-12-10 09:52
            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();
            }
    
    0 讨论(0)
  • 2020-12-10 09:58

    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.

    0 讨论(0)
提交回复
热议问题