RKGG爱吃鱼 2017-11-06 05:06 采纳率: 50%
浏览 4397
已结题

java中将一个byte[]数组写成一个二进制文件?

如题:想要将一个byte[]数组大概是1024*8这样大小的一个数组写成一个二进制文件,但是写入的时候发现会有数据丢失,不知道因为什么啊?
下面是代码,请大牛给解答一下,谢谢啦!
OutputStream os;
FileOutputStream fos;
try {
os = new FileOutputStream(file);
BufferedInputStream is = new BufferedInputStream(new ByteArrayInputStream(bs));
int len;
byte[] buf = new byte[1024 * 8];
while ((len = is.read(buf)) != -1) {
Thread.sleep(1000);
os.write(buf);
}
System.out.println("len:"+len);
os.flush();
is.close();
os.close();
System.out.println("写入成功:" + strPath);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}


  • 写回答

1条回答

  • noWayBinding 2017-11-06 06:27
    关注

    你这个代码有问题呀:

     import java.io.BufferedInputStream;
    import java.io.ByteArrayInputStream;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    
    public class Test {
        public static void main(String[] args) {
            OutputStream os;
            FileOutputStream fos;
            File file = new File("/home/gongxufan/out");
            try
    
            {
                os = new FileOutputStream(file);
                int len;
                byte[] buf = new byte[1024 * 8];
                BufferedInputStream is = new BufferedInputStream(new ByteArrayInputStream(buf));
                while ((len = is.read(buf)) != -1) {
                    Thread.sleep(1000);
                    os.write(buf);
                }
                System.out.println("len:" + len);
                os.flush();
                is.close();
                os.close();
                System.out.println("写入成功:" + file.getAbsolutePath());
            } catch (
                    FileNotFoundException e)
    
            {
                e.printStackTrace();
            } catch (
                    IOException e)
    
            {
                e.printStackTrace();
            } catch (
                    InterruptedException e)
    
            {
                e.printStackTrace();
            }
        }
    }
    
    
     gongxufan@gongxufan-ThinkPad-E460 ~ $ ll out 
    -rw-rw-r-- 1 gongxufan gongxufan 8192 Nov  6 14:24 out
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?