FileOutputStream中的write方法如何截断int类型参数 [英] how write method in FileOutputStream truncates the int type argument

查看:256
本文介绍了FileOutputStream中的write方法如何截断int类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

write()方法采用int格式,但会截断前3个字节并将该字节写入流中。
如果文件包含ASCII值大于127的字符,并且从文件中读取字节,然后将其写入输出流(另一个文本文件),它将如何显示它,因为在Java中,字节的最大值可以为+127

write() method in FileOutputStream takes an int but truncates the first 3 bytes and writes the byte to stream. If a file contains characters whose ASCII value is more than 127 and bytes are read from it and then written to output stream(another text file) how will it display it because in Java bytes can have a max value of +127.

如果文本文件(input.text)具有字符'›',其ASCII值为155。
输入流input从中读取:
int in = new FileInputStream( input.txt)。read(); // in = 155

If a text file(input.text) has character '›' whose ASCII value is 155. An input stream,input, reads from it : int in= new FileInputStream("input.txt").read();//in = 155

现在它写入另一个文本文件(output.txt)

Now it writes to another text file(output.txt)

new FileOutputStream( output.txt)。write(in );

此处的整数 in被截断为相应的十进制值字节-101。
即使它有关的信息似乎已经丢失,它如何成功地将字符写到文件上?

Here integer "in" is truncated to byte which will have corresponding decimal value : -101. How it successfully manages to write the character to file even though information about it seems to have been lost?

刚才我对write( int)方法,我观察到的是

Just now i went through the description of write(int) method in java docs and what i observed was


写入的一般约定是将一个字节写入输出流。要写入的字节是参数b的八个低位。 b的24个高阶位被忽略

所以我认为这与我的想法相反更早的时间(将write()中的int截断,就像将整数向下转换为大于127的字节时发生的情况一样),仅忽略24个高阶位,并且仅考虑8个最低有效位。
没有截断和转换为字节。
我想我是正确的。

So i believe that contrary to what i thought earlier(the int in write() is truncated as would happen while downcasting an integer to byte for values greater than 127) the 24 high order bits are only ignored and only 8 least significant bits are considered. No truncation and conversion to byte occurs. I guess i am correct.

推荐答案

我认为您的困惑是由字符集规范通常引起的认为字节是无符号的,而Java将字节视为带符号的。

I think your confusion is caused by the fact that specs for character sets typically take the view that bytes are unsigned, while Java treats bytes as signed.

实际上 155 是无符号字节 -101 作为有符号字节。 ( 256-101 == 155 )。位模式相同。只是您是否 将其视为已签名或未签名。

In fact 155 as an unsigned byte is -101 as a signed byte. (256 - 101 == 155). The bit patterns are identical. It is just a matter of whether you think of them as signed or unsigned.

截断的编码方式是特定于实现的。但是不会丢失任何信息……假设您首先有一个8位代码。

How the truncation is coded is implementation specific. But there is no loss of information ... assuming that you had an 8-bit code in the first place.

这篇关于FileOutputStream中的write方法如何截断int类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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