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

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

问题描述

这可能已经在别处得到了回答,但是您如何获得 int 值的字符值?

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

具体来说,我正在从 tcp 流中读取 a,而 reader .read() 方法返回一个 int.

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

我如何从中获取字符?

推荐答案

如果您尝试将流转换为文本,您需要知道要使用哪种编码.然后,您可以将字节数组传递到 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) 来读取一个更有效和方便一次整块文本.不过不要忘记检查返回值,看看有多少字符被读取.

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天全站免登陆