字节流:以字节为单位进行读写,二进制文件:图片,音频,视频等非字符数据只能用字节流来操作。
package com.gc.file;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class InputStreamDemo {
/**
* 字节流---底层以byte为单位进行操作
* 字符流不能读取字节文件,只能用来读取文本数据
* 字符流1次读取2个字节,而字节流1次只读取1个字节
*
* 字节流用来处理图片、音频、视频等字节文件
* 对于字符文件,使用专门的字符流操作!
* @throws IOException
*/
public static void main(String[] args) throws IOException {
//以下使用字节流操作文本数据,仅为了演示字节流的用法,真正操作字符数据,请使用Reader和Writer!
writeFileWithOutputStream();
readFileWithInputStream();
copyFileWithBuffer();
copyFileWithJavaBuffer();
}
/**
* 使用java提供的缓冲区对象进行操作
* 很奇怪,如果不自定义一个缓冲区,拷贝很慢
* 所以,还是自定义一个缓冲区来使用
* 哎,这是为什么呢?
* @throws IOException
*/
private static void copyFileWithJavaBuffer() throws IOException {
FileInputStream fis = new FileInputStream("temp\\a.jpg");
FileOutputStream fos = new FileOutputStream("temp\\b.jpg");
BufferedInputStream bufis = new BufferedInputStream(fis);//缓冲读
BufferedOutputStream bufos = new BufferedOutputStream(fos);//缓冲写
byte[] bBuf = new byte[1024];//仍然提供外部缓冲区,不然读写很慢
int len = 0;
while((len=fis.read(bBuf))!=-1) {
fos.write(bBuf,0,len);
}
bufis.close();//内部会调用fis.close()
bufos.close();//内部会调用fos.close()
}
/**
* 自定义缓冲区来操作
* @throws IOException
*/
private static void copyFileWithBuffer() throws IOException {
FileInputStream fis = new FileInputStream("temp\\a.jpg");
FileOutputStream fos = new FileOutputStream("temp\\b.jpg");
byte[] bBuf = new byte[1024];//操作字节数据,定义字节数组作为缓冲区(而操作字符数据,则定义字符数组作为缓冲区)
int len = 0;
while((len=fis.read(bBuf))!=-1) {
fos.write(bBuf, 0, len);
//fos.flush();//这里的flush()没有任何用,因为方法的实现为空
}
fis.close();
fos.close();
}
private static void readFileWithInputStream() throws FileNotFoundException,
IOException {
FileInputStream fis = new FileInputStream("temp\\byte.txt");
byte[] buf = new byte[1024];
int len = 0;
while((len=fis.read(buf))!=-1) {
System.out.println(new String(buf,0,len));
}
}
private static void writeFileWithOutputStream()
throws FileNotFoundException, IOException {
FileOutputStream fis = new FileOutputStream("temp\\byte.txt");
byte[] b = "hello".getBytes();
fis.write(b);
fis.close();
}
}