有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将文件转换为十六进制转储

我的输出反映了我需要处理成十六进制值的文件,但我的十六进制值没有反映在输出中。为什么我的文件没有被转换成十六进制值

public class HexUtilityDump {

public static void main(String[] args) {
    FileReader myFileReader = null;
    try {
        myFileReader = new FileReader("src/hexUtility/test.txt");
    } catch(Exception ex) {
        System.out.println("Error opening file: " + ex.getLocalizedMessage());
    }
    BufferedReader b = null; 
    b = new BufferedReader(myFileReader);

    //Loop through all the records in the file and print them on the console
    while (true){ 
        String myLine; 
        try {
            myLine = b.readLine();
            //check for null returned from readLine() and exit loop if so. 
            if (myLine ==null){break;} 
            System.out.println(myLine); 
        } catch (IOException e) {
            e.printStackTrace();
            //it is time to exit the while loop
            break; 
        }
    }
} 

下面是通过转换提取文件的代码

public static void convertToHex(PrintStream out, File myFileReader) throws IOException {
    InputStream is = new FileInputStream(myFileReader);

    int bytesCounter =0;        
    int value = 0;
    StringBuilder sbHex = new StringBuilder();
    StringBuilder sbText = new StringBuilder();
    StringBuilder sbResult = new StringBuilder();

    while ((value = is.read()) != -1) {    

        //convert to hex value with "X" formatter
        sbHex.append(String.format("%02X ", value));

        //If the character is not convertible, just print a dot symbol "." 
        if (!Character.isISOControl(value)) {
            sbText.append((char)value);
        } else {
            sbText.append(".");
        }

        //if 16 bytes are read, reset the counter, 
        //clear the StringBuilder for formatting purpose only.
        if(bytesCounter==15) {
            sbResult.append(sbHex).append("      ").append(sbText).append("\n");
            sbHex.setLength(0);
            sbText.setLength(0);
            bytesCounter=0;
        }else{
            bytesCounter++;
        }
    }

    //if still got content
    if(bytesCounter!=0){            
        //add spaces more formatting purpose only
        for(; bytesCounter<16; bytesCounter++){
            //1 character 3 spaces
            sbHex.append("   ");
        }
        sbResult.append(sbHex).append("      ").append(sbText).append("\n");
    }

    out.print(sbResult);
    is.close();
}

共 (1) 个答案

  1. # 1 楼答案

    如果从不调用convertToHex,请从main()方法中删除文件读取。看来你想做些什么

    File f = new File("src/hexUtility/test.txt");
    convertToHex(System.out, f);