输入输出流的 read(char[] buff) 方法的返回值?

Quincy650 2018-01-06 05:37:39
求助大佬。
在学习输入输出流,不太了解read()方法的返回值。
import java.io.IOException;
import java.io.StringReader;

//介绍已字符串作为节点的节点流,StringReader和StringWriter
//把字符串的内容放入流中,或者把流的内容放入字符串中(可变字符串:StringBuffer或StringBuilder)
public class StringStream {

public static void main(String[] args) {
String string0 = "Good Good Study\nDay Day up!";
printInfo(string0);

}

// 使用StringReader类实现将字符内容在控制台输出
public static void printInfo(String string) {
// 字符串输入流
StringReader reader = new StringReader(string);
// 数组
char[] buff = new char[1000];
try {
while ((reader.read(buff)) > 0) {
System.out.print(new String(buff, 0, reader.read(buff)));
}
reader.close();
} catch (IOException e) {
System.out.println("读取字符串内容失败");
e.printStackTrace();
}

}

}

报错如下:


求助大家,感谢。
...全文
427 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Lie_lei 2018-01-07
  • 打赏
  • 举报
回复
public class Dmeo { public static void main(String[] args) { String str = "Hello.....hello"; printInfo(str); } private static void printInfo(String str) { StringReader sr = new StringReader(str); char[] buf = new char[1024];//接收输入流里字符数据 int count = 0;//记录要读的字符流里有几个字符 try { while ((count = sr.read(buf)) != -1) {//read方法要读到一个字符数组中去,read如果读完会返回一个-1表示文件读完. System.out.printf(new String(buf,0,count));//将字符数组中的第一个到第count个转换成字符串输出 } } catch (IOException e) { e.printStackTrace(); } finally { sr.close(); } } }
Lie_lei 2018-01-06
  • 打赏
  • 举报
回复
你好,reader.read读到文件末尾的话,是返回一个-1,它的返回值是一个整型,表示读取到的字符数

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧