是不是所有的输出流最后都要用flush方法?
因为老师在缓冲输出流那里才开始说的flush方法,我一直以为只有缓冲输出流才需要用flush方法,可是在字节字符转换流这一节中老师对字节字符转换流也使用了flush方法,然后我去查了一下官方API,发现字节输出流FileOutputStream中也有flush方法,那么是不是字节输出流的write方法也是和缓冲输出流一样在没有满的时候无法自动执行write操作?
如果按照上面所说,那么下面代码没用用到flush方法,为何依然能成功write?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | package com.imooc.input_output_stream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;public class FileOutputStreamDemo3 { public static void main(String[] args) { //文件拷贝,实际上就是字节数据经输入流输入再经输出流输出到另一个文件的过程 try { //创建读取图片数据的输入流 FileInputStream fis=new FileInputStream("happy.png"); //创建输出图片数据的输出流 FileOutputStream fos=new FileOutputStream("happycopy.png"); int n; byte[] b=new byte[1024]; while((n=fis.read(b))!=-1) { fos.write(b,0,n);//用这种多参数的write方法可以保证不会写入多余的数据 } fis.close(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }} |
在附上老师这节的代码
package com.imooc.reader_writer;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class ChangeStreamDemo
{
public static void main(String[] args)
{
try
{
FileInputStream fis=new FileInputStream("imooc.txt");
/*
* 将字节输入流转换为字符输入流
* public InputStreamReader(InputStream in)
*/
InputStreamReader isr=new InputStreamReader(fis);
int n;
char[] cbuf=new char[10];
/*
* public int read() throws IOException
* ————从输入流读取单个字符,返回读取的字符数据(转换为int类型)
* public int read(char[] cbuf) throws IOException
* ————从输入流读取最多cbuf.length个字符的数据,存放在字符数组cbuf中,返回实际读取的字符数
* public String(char[] value,int offset,int count)
* ————从字符数组value的offset位置开始,创建一个长度为count的字符串
*/
/*
* 以下注释代码为读取的步骤,由于这个步骤会导致下面的输出流的例子出错,因此注释掉
while((n=isr.read(cbuf))!=-1)
{
System.out.print(new String(cbuf,0,n));//保证最后一次在未将数组cbuf存满的时候也能正确输出
}
*/
//字节输出流转字符输出流
FileOutputStream fos=new FileOutputStream("imooc1.txt");
/*
* public OutputStreamWriter(OutputStream out)
* ————将基础字节输出流转换为字符输出流
* public void write(char[] cbuf,int off,int len) throws IOException
* ————将cbuf字符数组中第off个位置开始长度为len的字符串输出到输出流中
*/
OutputStreamWriter osw=new OutputStreamWriter(fos);
while((n=isr.read(cbuf))!=-1)
{
osw.write(cbuf,0,n);
osw.flush();
}
fis.close();
fos.close();
isr.close();
osw.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}188
收起
正在回答
1回答
flush方法是字节输出流的抽象父类OutputStream的方法,所以每个字节输出流类都会有flush方法。但是有些没有缓冲区的类flush方法只是被重写了,但什么都不做,也就是方法体是为空的。所以FileOutputStream调用flush方法什么都没做。另外,close方法也会强制清空缓冲区,因此不写flush也是可以的,但对于不能马上调用close方法的,还是需要用flush方法强制清空一下。毕竟一旦调用close方法,这个流对象也就不能用了。如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
Android零基础入门2018版
- 参与学习 人
- 提交作业 5461 份
- 解答问题 7235 个
此次推出的专题为Android攻城狮培养计划的第一部分语法与界面基础篇,将带大家从0开始学习Android开发。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星