求助

Brave_ly 2012-06-02 12:51:47
一个简单的io流问题,btn_show为显示按钮,单击按钮输入指定内容,但是在读的时候遇到下面问题,求解。
btn_show.addActionListener(new ActionListener(){
byte[]data = new byte[10];
FileInputStream in = null;
public void actionPerformed(ActionEvent e) {
StringBuffer sb = new StringBuffer();
try {
in = new FileInputStream("F:\\io\\date.txt");
try {
int count = -1;
while((count=in.read(data)) != -1) {
sb.append(new String(data,0,count));
}
txt_show.setText(sb.toString());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}finally {
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}

});
上段为正常代码,运行没有问题。
btn_show.addActionListener(new ActionListener(){
StringBuffer sb = new StringBuffer();
public void actionPerformed(ActionEvent e) {
FileInputStream in = null;
byte []b = new byte[10];
try {
in = new FileInputStream("F:\\io\\date.txt");
int count = -1;

while((count = in.read(b)) != -1);{
sb.append(new String(b,0,count));
}
txt_show.setText(sb.toString());
}
catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}finally {
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}

});
此段为问题代码,运行报“字符串下标越界”异常。

我仔细看了一个多小时,就是没看出差别,但是下部分的代码运行就是有问题,求解答迷惑。
...全文
97 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Brave_ly 2012-06-02
  • 打赏
  • 举报
回复
感激啊,兄弟。
RDroid 2012-06-02
  • 打赏
  • 举报
回复
while((count = in.read(b)) != -1);{
sb.append(new String(b,0,count));
}


注意,这里while后面跟了一个分号

等循环结束时,count=-1
那么 sb.append(new String(b,0,count)); 就报异常了

62,621

社区成员

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

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