流:流(stream)的概念源于 UNIX 中管道(pipe)的概念,在 UNIX 中,管道是一条不间断的字节流,用来实现程序或进程间的通信,或读写外围设备、外部文件等。
重要:
**1.流操作结束后必须关闭。
2.InputStream、Reader、OutputStream、Write全是抽象,不能直接实例化**
每一个都有很多子类,在此不列举了。
输入流—》只能读,不能写====》从磁盘等外设到内存=====>对应jdk中InputStream(字节流)Reader(字符流)
返回-1则读取完毕。
输出流—》只能写,不能读====》从内存到其他地方=====》对应jdk中OutputStream(字节流)Write(字符流)
write方法会将原来的清空掉从新写。
如果想要添加在后面创建时添加true
OutputStream os = new FileOutputStream(file,true(默认否))
复制实现:
1.将文件读取到字节数组中====》如果文件过大,大于服务器内存,则使用此方法就不合适。
public void fileTest(){
//路径分隔符
String separator = File.separator;
//路径为自己电脑上的文件路径
File nfile = new File("D:"+separator+"java"+separator+"204"+separator+"Video_2018-05-02_202039.wmv");
File mfile = new File("D:"+separator+"java"+separator+"205"+separator+"Video_2018-05-02_202039.wmv");
try {
InputStream is = new FileInputStream(nfile);
OutputStream os = new FileOutputStream(mfile);
byte[] fileBytes = new byte[(int)nfile.length()];
/*
* 读取数据,从第几个开始读取多少,返回是bytes的大小
* 或者-1===》当读取完毕之后返回-1
*/
int data = is.read(fileBytes,0,fileBytes.length);
while(data!=-1){
//同读取
os.write(fileBytes);
//向下读取
data = is.read(fileBytes);
}
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
2.分段读:速度快
public void fileTest1(){
//路径分隔符
String separator = File.separator;
//路径为自己电脑上的文件路径
File nfile = new File("D:"+separator+"java"+separator+"204"+separator+"Video_2018-05-02_202039.wmv");
File mfile = new File("D:"+separator+"java"+separator+"205"+separator+"Video_2018-05-02_202039.wmv");
try {
InputStream is = new FileInputStream(nfile);
OutputStream os = new FileOutputStream(mfile);
//在此设置读取字段数4M
byte[] fileBytes = new byte[4096];
int data = is.read(fileBytes,0,fileBytes.length);
while(data!=-1){
//同读取
os.write(fileBytes);
//向下读取
data = is.read(fileBytes);
}
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
字符字节流区别:
1.字符流使用了缓冲区,而字节流没有使用缓冲区。
2.字符流操作Unicode字符数据,字节流操纵字节
3.实际开发中使用字节多,因为数据是以字节储存在电脑中的