字节流三步走:

  1. 创建字节输出流对象
  2. 写数据
  3. 释放资源

换行符

windows\r\n

linux\n

mac\r

字节流写数据的三种方式

1
2
3
void write(int b);							//以此写一个字节数据
void write(byte[]b); // 一次写一个字节数组数据
void write(byte[]b,int off,int len); //一次写一个字节数组的部分数据

读取文件案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 简单的读取文件流程
* @throws IOException
*/
private static void readFile() throws IOException {
// 读取文件
FileInputStream fis = new FileInputStream("p:/test/a.txt");
int cha; // 定义每次读取的内容存放介质
while ((cha = fis.read())!=-1){
//输出内容
System.out.println((char)cha);
}
//释放资源
fis.close();
}

复制文件

简单复制

1
2
3
4
5
6
7
8
9
10
11
12
private static void copyFile() throws IOException {

FileOutputStream fileOutputStream = new FileOutputStream("./a.txt");
FileInputStream fileInputStream = new FileInputStream("v:/study/a.txt");

int b ;
while ((b = fileInputStream.read())!=-1){
fileOutputStream.write(b);
}
fileInputStream.close();
fileOutputStream.close();
}

使用byte[]提高复制效率

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 利用字节数组提高复制效率
* @throws IOException
*/
private static void copymedia() throws IOException {
FileOutputStream fos = new FileOutputStream("./a.mp4");
FileInputStream fis = new FileInputStream("P:\\Study\\self-study\\Java\\2阶段二:JavaSE进阶\\第二章 2-Stream & IO\\0-1 Stream\\01-Stream流-初体验.mp4");
byte [] bytes = new byte[1024];
int len;
while((len = fis.read(bytes))!=-1){
fos.write(bytes,0,len);
}
fis.close();
fos.close();
}

使用字节缓冲byte[]

1
2
3
4
5
6
7
8
9
10
11
12
private static void copyBufferArr() throws IOException {
BufferedInputStream bis = new BufferedInputStream(new BufferedInputStream(new FileInputStream("P:\\Study\\self-study\\Java\\2阶段二:JavaSE进阶\\第二章 2-Stream & IO\\0-1 Stream\\01-Stream流-初体验.mp4")));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("./copy.mp4"));

byte [] bytes= new byte[1024];
int len;
while ((len = bis.read(bytes))!=-1){
bos.write(bytes,0,len);
}
bis.close();
bos.close();
}

小结

字节流:

可以操作(拷贝)所有类型的文件

字节缓冲流:

可以提高效率
不能直接操作文件,需要传递字节流

拷贝文件的四种方式:

  1. 字节流一次读写一个字节
  2. 字节流一次读写一个字节数组
  3. 字节缓冲流一次操作一个字节
  4. 字符缓冲流一次操作一个字节数组