为什么ByteArrayOutputStream和ByteArrayInputStream的内容不一样?

时间:2016-06-29 07:20:43

标签: java byte bytearray inputstream bytearrayoutputstream

英文:

我在Java中的一个单元测试中遇到了一个大问题。我将一个字节数组与一个InputStream进行比较,但是得不到相同的结果。

示例如下。

感谢您给我的帮助! :)

Français:

Bonjour tout le monde!

J'ai ungrosprollèmelorsd'un de mes测试单元en java。 Je dois comparer un tableau d'octet avec un objet InputStream et je n'obtiens paslemêmerésultat。

L'exemple est plus bas。

Merci pour l'aide que vous pourrez m'apporter! :)

示例:

public final class ByteGetInputStreamExampleProblem
{
    public static void main( final String[] args ) throws Exception
    {
        final SecureRandom s = new SecureRandom() ;

        final ByteArrayOutputStream bos = new ByteArrayOutputStream() ;

        long bPut = 0 ;

        final byte[] buffer = new byte[ 2 ] ;

        while( bPut < 10 )
        {
            s.nextBytes( buffer ) ;
            bos.write( buffer ) ;
            bPut += buffer.length ;
        }

        final InputStream is = new ByteArrayInputStream( bos.toByteArray() ) ;

        System.out.print("A = ");

        for( int i = 0 ; i < bos.size() ; i++ )
            System.out.print( bos.toByteArray()[i] + ";" ) ;

        System.out.print("\nB = ");

        int c ;
        while( ( c = is.read() ) != -1 )
            System.out.print(c + ":");
    } ;
} ;

输出/排序:

A = -3; -47; -121; 37; -73; 83; 109; -54; 20; 106;

B = 253:209:135:37:183:83:109:202:20:106:

1 个答案:

答案 0 :(得分:3)

打印A的内容时,将它们打印为字节。因此,它会在Byte.MIN_VALUEByte.MAX_VALUE-128127)之间打印值。

当您使用is.read()时,您将内容读作以int传递给您的无符号数字。该值介于0255之间。

您可以通过将c转换为字节来获得相同的输出,例如

while( ( c = is.read() ) != -1 ){
    byte b = (byte)c;
    System.out.print(b + ":");
}

从本质上讲,您需要将这两个数字转换为0255之间或-128127之间。

您可以将0转换为255范围,将-128转换为127,将其转换为字节。

您可以通过执行-128127转换为value & 0xFF。这会将其更改为0 - 255范围内。

read()ByteArrayInputStream的代码如下:

public synchronized int read() {
    return (pos < count) ? (buf[pos++] & 0xff) : -1;
}