Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

bytearray - How to print raw byte content from a byte[] array to stdout in Java?

I am doing the same project as describe here:

Wrap deflated data in gzip format

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]);
    }

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.

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?

EDIT:

To be more specific:

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming your byte array is called buf:

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

Edit: 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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...