如何在 Java 中将字节 [] 数组中的原始字节内容打印到标准输出? [英] How to print raw byte content from a byte[] array to stdout in Java?

查看:26
本文介绍了如何在 Java 中将字节 [] 数组中的原始字节内容打印到标准输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做与此处描述相同的项目:

I am doing the same project as describe here:

以 gzip 格式包装压缩的数据

我的问题是当我尝试打印字节时,我得到了奇怪的结果.我的问题出现在以下代码中(对不起,我选择了错误的变量):

My problem is that when I try to print out bytes, I get weird results. My problems occur in the following code(Sorry for my bad choice of variables):

    for(int k = 0; k < head.length; k++){
        System.out.write(head[k]);
    }

    for(int m = 0; m < a.size(); m++){
        int comprlength = a.get(m).getclength();
        for(int ii = 0; ii < comprlength; ii++){
            System.out.write(a.get(m).getcompr()[ii]);
        }
    }
    for(int j = 0; j < f1.length; j++){
        System.out.write(f1[j]);
    }
    for(int ll = 0; ll < total_d.length; ll++){
        System.out.write(total_d[ll]);
    }

最后两个 for 循环不打印出它们的字节数组的内容.因此,我在使用 gzip 时遇到了意外的文件结尾错误.奇怪的是,如果我注释掉第二个 for 循环块(带有变量 m 和 ii 的块),什么也不会打印出来.

The last two for-loops do not print out the contents of the their byte arrays. Thus I get a unexpected end of file error when using gzip. The weird thing is that if I comment out the second for-loop block (the block with the variables m and ii), nothing gets printed out.

那么如何正确打印出字节数组的内容呢?为什么第一个 for 循环在第二个 for 循环没有注释时正确打印出来,为什么如果第二个 for 循环被注释了,它为什么不打印任何东西?

So how do I properly print out the contents of my byte arrays? Why does the first for-loop print out properly when the second for-loop is not commented and why does it not print anything if that second for-loop is commented?

更具体地说:

我想写出原始字节.我想这样做,以便我的每个字节数组都紧随其后

I want to write out the raw bytes. And I want to do it so that it is right after each other for every one of my byte arrays

推荐答案

假设你的字节数组被称为buf:

Assuming your byte array is called buf:

 System.out.println(Arrays.toString(buf));

听起来您真正想做的是将字节写入标准输出,而不是打印它们.请参阅 http://docs.oracle.com/javase/6/docs/api/java/io/PrintStream.html 了解打印到流和写入流之间的区别.最简单的方法应该是调用 write(byte[] b) 方法:

It sounds like what you really want to do is write your bytes to stdout, not print them. See http://docs.oracle.com/javase/6/docs/api/java/io/PrintStream.html for the difference between printing to a stream and writing to it. Easiest way should be to call the write(byte[] b) method:

System.out.write(buf);

这篇关于如何在 Java 中将字节 [] 数组中的原始字节内容打印到标准输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆