一、字节流的两个父类:
InputStream :
OutputStream:
二、首先看:OutputStream:
1、API:
2、继承体系:
媒体数据也是以文件形式存在。
3、方法:
4、代码演示:
private static void demo_writer() throws IOException {
//1、创建字节输出流对象。用于操作文件
FileOutputStream fos = new FileOutputStream("byte.txt");
//2、写数据 直接到了目的地
//将String转换为Byte
fos.write("fefnjnejfe".getBytes());
//无效。源码是空的。在其他地方有实现。在此不需要刷新。
//fos.flush();
//关闭流
fos.close();
}
三、InputStream
1、API
2、继承体系
3、方法:以FileInuputStream为例:
4、代码演示:
private static void demo_reader() throws IOException {
//1、创建字节读取流对象。用于读取文件
FileInputStream fis =new FileInputStream("byte.txt");
/* // 读取数据一次读取 一个字符
int ch=fis.read();
System.out.println((char)ch);*/
//一次性全部读取
/* int ch=0;
while ((ch=fis.read())!=-1){
System.out.println((char)ch);
}*/
/**
* 返回从此输入流中可以读取(或跳过)的剩余字节数的估计值
*/
System.out.println(fis.available()); //10
//加入缓冲区。提高效率 全部读取
//建议使用这种
/* byte[] bytes = new byte[1024];
int len=0;
while ((len=fis.read(bytes))!=-1){
System.out.println(new String(bytes,0,len));
}*/
// 若文件较大,可能导致内存溢出
byte[] bytes = new byte[fis.available()];
fis.read(bytes);
System.out.println(new String(bytes));
fis.close();
}
四、 复制媒体文件 MP4
第一种://自定义缓冲区
//自定义缓冲区
private static void copy_1() throws IOException {
FileInputStream fis = new FileInputStream("G:\\basketball.mp4");
FileOutputStream fos = new FileOutputStream("G:\\1.mp4");
byte[] bytes= new byte[1024];
int len=0;
while ((len=fis.read(bytes))!=-1){
fos.write(bytes,0,len);
}
fos.close();
fis.close();
}
第二种:使用API中给我们提供的缓冲区
//使用API中给我们提供的缓冲区
private static void copy_2() throws IOException {
//文件读取流
FileInputStream fis = new FileInputStream("G:\\basketball.mp4");
//读取缓冲区
BufferedInputStream bufis=new BufferedInputStream(fis);
//文件输出流
FileOutputStream fos = new FileOutputStream("G:\\2.mp4");
//输出缓冲区
BufferedOutputStream bufos=new BufferedOutputStream(fos);
int ch=0;
while ((ch=bufis.read())!=-1){
bufos.write(ch);
bufos.flush();
}
bufos.close();
bufis.close();
}
第三种:不使用循环 不建议使用,文件过大时可能导致内存溢出
//不使用循环 不建议使用,文件过大时可能导致内存溢出
private static void copy_3() throws IOException {
FileInputStream fis = new FileInputStream("G:\\basketball.mp4");
FileOutputStream fos = new FileOutputStream("G:\\3.mp4");
byte[] bytes=new byte[fis.available()];
fis.read(bytes);
fos.write(bytes);
fos.close();
fis.close();
}
第四种:读一个字节写一个。效率非常慢,不要使用
//读一个字节写一个。效率非常慢,不要使用
private static void copy_4() throws IOException {
FileInputStream fis = new FileInputStream("G:\\basketball.mp4");
FileOutputStream fos = new FileOutputStream("G:\\4.mp4");
int ch=0;
while ((ch=fis.read())!=-1){
fos.write(ch);
}
fos.close();
fis.close();
}
五、能使用字符流复制 "照片文件"吗?
有可能成功。但是照片会打不开。原因是,字符流读取到文件以后,对照ASCII码表。文字有特定的编码格斯,而媒体文件却没有,码表会使用未知字符区的一些数字来表示对应的情况,当图片解析以后,源数据和复制的不一致,图片解析器无法解析,所以图片打不开。