2013-10-30 95 views
0

早上好,我有一個serius問題。 我需要讀取十六進制文件並將其轉換爲ascii。 我還需要在另一個文件上寫入ascii。 我試過這樣:在java中讀取hex文件並將其轉換爲ascii

/** 
* @param args the command line arguments 
*/ 
public static void main(String[] args) throws FileNotFoundException, IOException { 
    FileInputStream in = new FileInputStream("fileAscii"); 
    int read; 
    String hex = ""; 
    int count = 0; 
    String valueRead=""; 
    PrintWriter writer= new PrintWriter("fileOutput"); 

    while ((read = in.read()) != -1) { 
     count++; 
     valueRead= Integer.toHexString(read); 
     if(valueRead.length()==1){ 
      hex=hex+"0"; 
     } 
     hex = hex + valueRead; 
     if (is16Multipler(count)) { 

      System.out.println(hex); 
      String sb = ""; 
      StringBuilder temp = new StringBuilder(); 
      for (int i = 0; i < hex.length() - 1; i += 2) { 

       //grab the hex in pairs 
       String output = hex.substring(i, (i + 2)); 
       //convert hex to decimal 
       int decimal = Integer.parseInt(output, 16); 
       //convert the decimal to character 
       sb=sb+(char) decimal; 


      } 
      if(!sb.equals("00000000000000000000000000000000")) 
      { 
       writer.println(sb.toString()); 
      } 


       hex = ""; 
     } 
    } 
} 


public static boolean is16Multipler(int number) { 
    if (number % 16 == 0) { 
     return true; 
    } 
    return false; 
} 

的問題是,我讀例如錯誤的價值觀讀83蝙蝠原始文件包含84

+0

該程序似乎將它讀取的字節轉換爲十六進制,而不是其他方式。 – Henry

+0

上面寫着這樣的:6f726b73686f702e636f6d002e466c0b 24d77901080009000000000014031f06 2e31616e64312e6974002e487b937d25是十六進制格式 –

+0

有沒有這樣的事,作爲一個「十六進制文件」。有二進制文件和文本。這是二元的。你現在的代碼做的是將二進制轉換爲十六進制,然後將十六進制轉換爲ASCII,但並不總是準確。這一點逃避了我。 – EJP

回答

2

此代碼將讀取你的輸入fileof十六進制和寫入文件作爲ASCII字符

public static void main(String[] args) throws FileNotFoundException, IOException { 
     BufferedReader br = new BufferedReader(new FileReader("fileAscii")); // to read a single line from the file 
     int read; 
     String src= new String();  // to store the string obtained from buffered reader 
     PrintWriter writer= new PrintWriter("fileOutput"); 
     src=br.readLine();    // read an input line from the file 

     while(src!=null){ 
      src=src.replace(" ", ""); // Trim out the spaces 
      for(int i=0;i<src.length();i+=2){ 
       read=Integer.parseInt(src.substring(i,i+2), 16); // convert the String to hex integer 
       writer.print((char)read);       // convert hex to char and write into file 
      } 
      src=br.readLine(); 
     } 
     writer.flush(); 
    } 
+0

我發現這個錯誤:線程「main」中的異常java.lang.NumberFormatException:對於輸入字符串:「 」 \t at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) \t at java.lang。 Integer.parseInt(Integer.java:492) \t at parser.Parser.main(Parser.java:35) Java結果:1 –

+0

解決:問題是記事本++。如果我打開輸出文件惠普記事本++結果文件是更多不同於真實文件。但如果我打開經典記事本的輸出文件,結果文件就是真正的文件。 非常感謝,如果我浪費了你的時間。 :D –

+0

請不要提及。值得爲你提供幫助。 – gispyDangre

相關問題