`
xitong
  • 浏览: 6191749 次
文章分类
社区版块
存档分类
最新评论

字符转换为输入流

 
阅读更多
字符变输入流的2种方法
  1. 用StringReader将字符串转化为Reader
  2. 用ByteArrayInputStream将字符串转化为InputStream. 还有一个类StringBufferInputStream也可以将String转化为InputStream,但是由于它只支持字符串中每个字符的低八位,所以已经被遗弃了。

PS: java.io.Reader 和 java.io.InputStream 组成了 Java 输入类。Reader 用于读入16位字符,也就是 Unicode 编码的字符;而 InputStream 用于读入 ASCII 字符和二进制数据。

可能用到:在使用socket向服务器发送指定格式的字符串时可能用到

示例代码如下:

public static InputStream getStringInputStream(String s) {
if (s != null && !s.equals("")) {
try {

ByteArrayInputStream stringInputStream = new ByteArrayInputStream(
s.getBytes());
return stringInputStream;
} catch (Exception e) {

e.printStackTrace();
}
}
return null;
}

public static Reader getStringReader(String s) {
if (s != null && !s.equals("")) {
try {

StringReader stringReader = new StringReader(s);
return stringReader;
} catch (Exception e) {

e.printStackTrace();
}
}
return null;
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics