java - 破坏二进制文件

标签 java io arraylist arrays

引用我的previous question .

我用以下方法制作了该程序:
程序首先从文件中读取2k数据并将其存储到字节数组中。
然后每个数据包要添加的数据也存储在一个数组中,并且都添加到一个数组列表中。 然后将数组列表写入文件的输出流。

代码在这里:

File bin=chooser.getSelectedFile();
int filesize=(int)bin.length();
int pcount=filesize/2048; 
byte[] file=new byte[filesize];
byte[] meta=new byte[12];
int arraysize=pcount*12+filesize;
byte[] rootfile=new byte[46];
ArrayList al = new ArrayList();
String root;
prbar.setVisible(true);
int mark=0;
String metas;
try{
    FileInputStream fis=new FileInputStream(bin);
    FileOutputStream fos=new FileOutputStream(bin.getName().replace(".bin", ".xyz"));
    ObjectOutputStream os=new ObjectOutputStream(fos);
    root="46kb"+"5678"+"0000"+pcount+"MYBOX"+"13"+"S208";
    rootfile=root.getBytes();
    for(int n=0;n<=pcount;n++)
    {
        fis.read(file, 0, 2048);
        mark=mark+2048;
        int v=(mark/filesize)*100;
        prbar.setValue(v);
        metas="02KB"+"1234"+n;
        meta=metas.getBytes();

        al.add(rootfile);
        al.add(meta);
        al.add(file);
    }
    os.writeObject(al.toArray());
}
catch(Exception ex){
    erlabel.setText(ex.getMessage());
}

程序运行没有任何错误,但文件创建不正确。 要么是方法错误,要么是代码错误。

请帮忙

最佳答案

您似乎正在编写自己的二进制格式,但您正在使用具有自己的 header 的 ObjectOutputStream。 writeObject 以让 Java 进程反序列化该对象的方式写入对象而不是数据,例如带有它的类层次结构和字段名称。

对于二进制文件,我建议您使用带有 BufferedOutputStream 的普通 DataOutputStream,这样会更高效并执行您想要的操作。

我还建议您在生成数据时写入数据,而不是使用 ArrayList。这将使用更少的内存,使代码更简单、更快。

<小时/>

我会写这样的代码

File bin = chooser.getSelectedFile();
int filesize = (int) bin.length();
int pcount = (filesize + 2048 - 1) / 2048;
byte[] file = new byte[2048];

FileInputStream fis = new FileInputStream(bin);
String name2 = bin.getName().replace(".bin", ".xyz");
OutputStream os = new BufferedOutputStream(new FileOutputStream(name2));
byte[] rootfile = ("46kb" + "5678" + "0000" + pcount + "MYBOX" + "13" + "S208").getBytes("UTF-8");

for (int n = 0; n < pcount; n++) {
    os.write(rootfile);
    byte[] metas = ("02KB" + "1234" + n).getBytes("UTF-8");
    os.write(metas);

    int len = fis.read(file);

    os.write(file, 0, len);
    int percent = 100 * n / pcount;
    prbar.setValue(percent);
}
ow.close();

关于java - 破坏二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12420430/

相关文章:

java - SSL 握手失败 Android 5.1

从长 UTC 时间戳到 JAVA UTC 到 EST

java - 多次从 ArrayList 追加会导致同时打印多个值吗?

java - 如何对数学运算字符串进行代数展开

java - 如何从文件中提取扩展名为 .csv 的文件名

java - 交换两个整数的函数

java - 访问嵌入资源时出错

Java无法打开具有相对路径的文件

无法从打开的文件中读取

java - 如何实现ListIterator?