基于字节和基于字符的输出流

Byte-based and Chracter-based OutputStreams

我必须制作一个生成 10000 个整数的应用程序,这些整数具有从 0 到 100000 的随机值,并将其写入本地系统上的文件。我必须用两种不同的方式来做——字节流和字符流,并比较生成文件的大小。这些文件带有非常奇怪的字符,并且它们的大小相同。这是应该的吗?

基于字节的流:

    Random rd = new Random();
    File outFile = new File( "Byte-based Stream.txt" );
    FileOutputStream fos = new FileOutputStream(outFile);

    for(int i=0;i<10000;i++){
        fos.write(rd.nextInt(100001));
    }

    fos.flush();
    fos.close();

基于字符的流:

    Random rd = new Random();
    File outFile = new File( "Character-based Stream.txt" );
    FileWriter fos = new FileWriter(outFile);

    for(int i=0;i<10000;i++){
        fos.write(rd.nextInt(100001));
    }

    fos.flush();
    fos.close();

正如您在问题中提到的那样,FileWriter 写入字符,而 FileOutputStream 写入二进制文件(字节流)。

确实,计算机中的一切都是比特,但编码除外。 FileWriter 将字符写入为人类可读的编码,而 FileOutputStream 写入字节流。

大小相同,因为您的默认编码每个字符应该有 32 位,而 java 中的整数每个数字也有 32 位。

另见

FileOutputStream

FileWriter

Primitive Data Types

Comparison of Unicode encodings

FileOutputStream.write 只写出一个 single byte

类似地FileWriter.write只写出一个single character

即使他们都拿了 int,他们也没有写出 int。相反,您必须使用

int rn = rd.nextInt( 1000001 );
byte[ ] bytes = new byte[ ] {
    ( byte ) ( ( rn >>>  0 ) & 0xFF ),
    ( byte ) ( ( rn >>>  8 ) & 0xFF ),
    ( byte ) ( ( rn >>> 16 ) & 0xFF ),
    ( byte ) ( ( rn >>> 24 ) & 0xFF )
};
fileos.write( bytes );

对于FileOutputStream

fos.write( Integer.toString( rd.nextInt( 100001 ) ) );

对于 FileWriter

FileWriter 是一个旧实用程序 class,使用默认平台编码(= 不可移植)。看起来你有一个单字节编码,因此大小相同。

以下

PrintWriter fos = new PrintWriter(outFile, "UTF-16LE");

应该加倍大小。

顺便说一句,字节版本使用低位字节 (& 0xFF)。