java inputstream编码格式,Java InputStream编码/字符集

Running the following (example) code

import java.io.*;

public class test {

public static void main(String[] args) throws Exception {

byte[] buf = {-27};

InputStream is = new ByteArrayInputStream(buf);

BufferedReader r = new BufferedReader(

new InputStreamReader(is, "ISO-8859-1"));

String s = r.readLine();

System.out.println("test.java:9 [byte] (char)" + (char)s.getBytes()[0] +

" (int)" + (int)s.getBytes()[0]);

System.out.println("test.java:10 [char] (char)" + (char)s.charAt(0) +

" (int)" + (int)s.charAt(0));

System.out.println("test.java:11 string below");

System.out.println(s);

System.out.println("test.java:13 string above");

}

}

gives me this output

test.java:9 [byte] (char)? (int)63

test.java:10 [char] (char)? (int)229

test.java:11 string below

?

test.java:13 string above

How do I retain the correct byte value (-27) in the line-9 printout? And consequently receive the expected output of the System.out.println(s) command (å).

解决方案

If you want to retain byte values, don't use a Reader at all, ideally. To represent arbitrary binary data in text and convert it back to binary data later, you should use base16 or base64 encoding.

However, to explain what's going on, when you call s.getBytes() that's using the default character encoding, which apparently doesn't include Unicode character U+00E5.

If you call s.getBytes("ISO-8859-1") everywhere instead of s.getBytes() I suspect you'll get back the right byte value... but relying on ISO-8859-1 for this is kinda dirty IMO.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值