黑马程序员技术交流社区
标题:
为什么我这个IO流关不掉??求解释
[打印本页]
作者:
442851994
时间:
2012-11-1 10:47
标题:
为什么我这个IO流关不掉??求解释
本帖最后由 442851994 于 2012-11-1 18:13 编辑
package cn.itcast;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class fuxi7 {
public static void main(String[] args) throws IOException {
InputStream is=System.in;
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("fw.txt"));
int len=0;
StringBuilder sb=new StringBuilder();
while(true){
//System.out.println(is.read());
len=is.read();
if(len=='\r'){
continue;
}
if(len=='\n'){
bos.write(sb.toString().getBytes());
sb.delete(0, sb.length());
}else{
sb.append((char)len);
}
}
bos.close();//这句话会报错,提示出现remove,就将我这句关闭流的话删掉了??
}
}
作者:
小灰灰
时间:
2012-11-1 11:06
本帖最后由 都彭韬 于 2012-11-1 11:14 编辑
因为你 while() 循环中 写的是死循环 你这样写就好了
public class fuxi7 {
public static void main(String[] args) throws IOException {
InputStream is=System.in;
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("fw.txt"));
int len=0;
StringBuilder sb=new StringBuilder();
boolean b=true;
while(is.read()!=-1){//这样写更好
//System.out.println(is.read());
len=is.read();
if(len=='\r'){
continue;
}
if(len=='\n'){
bos.write(sb.toString().getBytes());
sb.delete(0, sb.length());
}else{
sb.append((char)len);
}
}
bos.close();//不会报错啦
}
复制代码
作者:
徐强
时间:
2012-11-1 11:10
while(true) 是个死循环,它后面的代码是不会被执行的,所有无论你打什么代码,都会报错的,可以改成这样。
public class fuxi7 {
public static void main(String[] args) throws IOException {
InputStream is=System.in;
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("fw.txt"));
int len=0;
StringBuilder sb=new StringBuilder();
while(is.read()!=-1){
//System.out.println(is.read());
len=is.read();
if(len=='\r'){
continue;
}
if(len=='\n'){
bos.write(sb.toString().getBytes());
sb.delete(0, sb.length());
}else{
sb.append((char)len);
}
}
is.close();
bos.close();
}
}
复制代码
作者:
李润根
时间:
2012-11-1 11:45
循环条件改成用变量表示,试试
boolean flag=true;
while(flag)
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2