簡體   English   中英

java-從byte []到File(十六進制值)的錯誤轉換

[英]java - ERROR converting from byte[] to File (hex values)

好的,我有一個包含一些HEX值的文件,還有一個將其與byte []一起使用的程序,以便轉換一些十六進制值,然后將其重新轉換為文件。 問題是,當我將字節數組重新轉換為文件時,某些十六進制值被修改,但我沒有發現問題。 如果您發現任何可能的錯誤,請不要猶豫。

如您所見,我有一個test.sav文件,這里是:

這是程序的結果,這兩個文件是不同的,並且它們應該是相同的,因為已經進行了任何更改:

這是代碼:

public class Test {

public static File file;
public static String hex;
public static byte[] mext;
public static byte[] bytearray;

public static void main(String[] args) throws IOException {
    file = new File("C:\\Users\\Roman\\Desktop\\test.sav");
    StringBuilder sb = new StringBuilder();
    FileInputStream fin = null;

    try {
        fin = new FileInputStream(file);
        bytearray = new byte[(int)file.length()];
        fin.read(bytearray);

        for(byte bytev : bytearray){ 
            sb.append(String.format("%02X", bytev));
        }
        System.out.println(sb);


    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {}

    //replaceMax(); <-- I deduced that conversion is not the problem 
    save(); // THIS IS THE IMPORTANT PART

}


public static void save() throws IOException{
    PrintWriter pw = new PrintWriter("C:\\Users\\Roman\\Desktop\\test2.sav");
    pw.write("");
    pw.close();
    FileWriter fw = new FileWriter(new File("C:\\Users\\Roman\\Desktop\\test2.sav"));
    BufferedWriter out = new BufferedWriter(fw);
    out.write(new String(bytearray, "ASCII"));
    out.close();
}

} 

您正在從二進制文件中讀取數據,然后嘗試將其作為字符流寫出。 此外,您還強迫它使用ASCII (7位字符集)作為字符編碼。

嘗試更改save方法以使用:

     FileOutputStream output = new FileOutputStream("C:\\Users\\Roman\\Desktop\\test2.sav");
     try {
         output.write(bytearray);
     } finally {
         output.close();
     }

這樣可以避免字符(重新)編碼的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM