缓冲流

用缓冲流复制文件
当使用处理流输出时,需要使用flush刷新流
1.使用节点流从磁盘将数据读取到内存的缓存区
首先构建输入流和输出流(src为源文件,des为目标文件)
//输入流
fis = new FileInputStream(src);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
//输出流
fos = new FileOutputStream(des);
osw = new OutputStreamWriter(fos);
bw = new BufferedWriter(osw);
2.将内存缓冲区的数据读到处理流对应的缓冲区
int ch = 0;
while(true){
ch = br.read();
if(ch == -1){
break;
}
bw.write(ch);
或者
while((ch = br.read()) != -1){
bw.write(ch);
}
3.处理流从处理流的缓冲区将数据读取到对应的地方
调用方法
bw.flush();

使用字节流
//字节缓冲输入输出流
FileInputStream fis = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
byte[] buffer = new byte[1024];
int len = 0;
try{
fis = new FileInputStream(src);
bis = new BufferedInputStream(fis);
fos = new FileOutputStream(des);
bos = new BufferedOutputStream(fos);

        while((len = bis.read(buffer)) != -1){
            bos.write(buffer);
        }
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        try {
            bos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

输出重定向 System.out->终端(重定向到自己的文件里)
PrintStream ps = null;
try{
ps = new PrintStream(new FileOutputStream(des));
System.setOut(ps);
System.out.println("测试文本");
}catch(Exception e){
e.printStackTrace();
}finally{
ps.close();
}
输入重定向
FileInputStream fis = null;
Scanner scanner = null;
try{
fis = new FileInputStream(src);
scanner = new Scanner(fis);
while(scanner.hasNext()){
System.out.println(scanner.next());
}
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容