在java中将int的流转换为char [英] Converting stream of int's to char's in java

查看:108
本文介绍了在java中将int的流转换为char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能已经回答了其他问题,但是你如何获得int值的字符值?

This has probably been answered else where but how do you get the character value of an int value?

特别是我正在从tcp流中读取一个并且读者.read()方法返回一个int。

Specifically I'm reading a from a tcp stream and the readers .read() method returns an int.

如何从中获取一个字符?

How do I get a char from this?

推荐答案

如果您尝试将流转换为文本,则需要了解要使用的编码。然后,您可以将一个字节数组传递到 String 构造函数并提供 Charset ,或使用 InputStreamReader ,带有相应的 Charset 而不是。

If you're trying to convert a stream into text, you need to be aware of which encoding you want to use. You can then either pass an array of bytes into the String constructor and provide a Charset, or use InputStreamReader with the appropriate Charset instead.

只需从 int 转换为 char 只有当你想要直接从流中读取字节时才能使用ISO-8859-1。

Simply casting from int to char only works if you want ISO-8859-1, if you're reading bytes from a stream directly.

编辑:如果已经使用 Reader ,然后将 read()的返回值转换为 char 是正确的方法(在检查它是否为-1之后)...但通常更有效和方便的是调用 read(char [],int,int)读取整个块o f一次发短信。不要忘记检查返回值,以查看已读取的字符数。

If you are already using a Reader, then casting the return value of read() to char is the right way to go (after checking whether it's -1 or not)... but it's normally more efficient and convenient to call read(char[], int, int) to read a whole block of text at a time. Don't forget to check the return value though, to see how many characters have been read.

这篇关于在java中将int的流转换为char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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