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

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条回答 默认 最新

  • qq381332153
    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
    
    点赞 评论

相关推荐