码迷,mamicode.com
首页 > 其他好文 > 详细

InputStream & OutputStream 使用方法以及注意事项

时间:2019-07-19 21:13:47      阅读:717      评论:0      收藏:0      [点我收藏+]

标签:注意   java   The   port   包括   范围   col   NPU   缓冲区   

 1 /*
 2  * To change this license header, choose License Headers in Project Properties.
 3  * To change this template file, choose Tools | Templates
 4  * and open the template in the editor.
 5  */
 6 package InputStream;
 7 
 8 import java.io.BufferedInputStream;
 9 import java.io.BufferedOutputStream;
10 import java.io.File;
11 import java.io.FileInputStream;
12 import java.io.FileOutputStream;
13 
14 /**
15  *
16  * @author steven
17  */
18 /*
19 IO 体系
20 字节流练习
21 InputStream 字节输入流为抽象接口 ,不能直接创建对象,可以通过其子类 FileInputStream来创建对象
22 格式为: InputStream is = new FileInputStream("文件路径");
23        或者:FileInputStream fis = new FileInputSteam("文件路径");
24        如果想提高效率,可以使缓冲流来包装,格式为:
25        BufferedInputStream bis = new BufferedInputStream(fis);
26        这种模式称为装修设计模式
27 OutputStream 字节输出流,也为抽象接口,不能直接创建对象,可以通过其子类FileOutputStream来创建对象
28 格式为:OutputStream os = new FileOutputStream("文件路径");
29         或者 FileOutputStream fos = new FileOutStream("文件路径");
30         如果向提高效率,可以使用高效缓冲流包装
31         格式为:BufferedOutputStream bos = new BufferedOutputStream(fos);
32 
33 */
34 public class InputStream_01 {
35     public static void main(String[] args) throws Exception {
36         File file = new File("c:\\test\\1.txt");//关联文件
37         FileInputStream fis = new FileInputStream(file);//创建字节输入流
38         BufferedInputStream bis = new BufferedInputStream(fis);//升级为高速缓冲输入流
39         
40         File copyfile = new File("c:\\copy.txt");//关联新的复制文件
41         FileOutputStream fos = new FileOutputStream(copyfile);//创建字节写出流
42         BufferedOutputStream bos = new BufferedOutputStream(fos);//升级为高速缓冲写出流
43         
44         byte[] buf = new byte[1024];//创建1kb的读取缓冲数组;
45         int len ;
46         while((len = bis.read(buf)) != -1){//读取内容记录在buf数组中;
47             bos.write(buf, 0, len);//带字符数组缓冲的高效写出流,格式为buf.write(buf,0,len)
48                                    //其中buf为缓冲数组,BufferedOutputStream本身具有8Kb的缓冲大小
49                                    //每一将数组中1kb的数据加载到8Kb的缓冲区中,待到8kb缓冲区全部装满后
50                                    //系统会自动的将缓冲区的8kb内容一次性全部刷新到磁盘文件中;
51                                    //0为写入的开始,len为写入的长度,范围为(0-len)包括0不包括len
52             bos.flush();//字节流不一定非要写刷新,但是在结束虚拟机之前一定要关闭缓冲流的写出,
53             bos.close();//否则写出的文件不能被写入到本地磁盘中,会被当做垃圾被虚拟机回收!
54             //System.out.print(new String(buf,0,len));
55         }
56     }
57     
58     
59     
60     
61 }

 

InputStream & OutputStream 使用方法以及注意事项

标签:注意   java   The   port   包括   范围   col   NPU   缓冲区   

原文地址:https://www.cnblogs.com/steven-system-start/p/Fight_Steven.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!