java - 从字节[]转换为文件(十六进制值)时出错

标签 java file hex arrays

好吧,我有一个包含一些十六进制值的文件,以及一个使用 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();
     }

这将避免字符(重新)编码问题。

关于java - 从字节[]转换为文件(十六进制值)时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27305812/

相关文章:

java - 循环依赖、递归类

java - Spring RabbitMQ 将新队列附加到现有监听器

java - 如何在我的应用程序粘贴文件时有效地显示进度条?安卓

python shutil.copytree - 忽略权限

hex - 如何使用radare2将.text部分转储到输出文件?

java - 十六进制字符数组转十进制

java - 在 android-priority-jobqueue 中检索当前 Activity 作业列表

java - 处理 Android Studio 的 NullPointerException lint 警告的正确方法

java - for 循环的问题,接收和利用输入

十六进制转二进制