Question

We are really stuck on this topic, this is the only code we have which converts a file into hex but we need to open a file and then for the java code to read the hex and extract certain bytes (e.g. the first 4 bytes for the file extension:

import java.io.*;
public class FileInHexadecimal
{        
    public static void main(String[] args) throws Exception 
    {                
     FileInputStream fis = new FileInputStream("H://Sample_Word.docx");                
     int i = 0;                
     while ((i = fis.read()) != -1) {                       
        if (i != -1) {                                
        System.out.printf("%02X\n ", i);
     } 
    }  
    fis.close();    
   }
}
Was it helpful?

Solution

Do not confuse internal and external representation - what you do when converting to hex is that you only create a different representation of the same bytes.

There is no need to convert to hex if you just want to read some bytes from the file - just read them. For example, to read the first four bytes, you can use something like

byte[] buffer = new byte[4];
FileInputStream fis = new FileInputStream("H://Sample_Word.docx");  
int read = fis.read(buffer);
if (read != buffer.length) {
    System.out.println("Short file!");
}

If you need to read data from an arbitrary position within the file, you might want to check RandomAccessFile instead of using a stream. RandomAccessFile allows to set the position where to start reading.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top