目录
字节流:
- 可以操作(拷贝)所有类型的文件
- 字节输入流:FileInputStream
- 字节输出流:FileOutputStream
直接缓冲流:
- 可以提高效率
- 不能直接操作文件,需要传递字节流
- 字节缓冲输入流:BufferedInputStream
- 字节缓冲输出流:BufferedOutputStream
拷贝文件的四种方式有那些?
- 字节流一次读写一个字节
- 字节流一次读写一个字节数组
- 字节缓冲流一次操作一个字节
- 字节缓冲流一次操作一个字节数组
下面是拷贝文件的代码实现:
import java.io.*;
public class InputOutput{
public static void main(String[] args) throws IOException {
//单字节拷贝
FileInputStream fis = new FileInputStream("day10\\src\\com\\wt\\homework\\HomeWork.txt");
FileOutputStream fos = new FileOutputStream("day10\\src\\com\\wt\\homework\\HomeWorkCopy.txt");
//copy1(fis, fos);//字节流单字节拷贝
//copy2(fis, fos);//字节流数组拷贝
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("day10\\src\\com\\wt\\homework\\HomeWork.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("day10\\src\\com\\wt\\homework\\HomeWorkCopyHuanchong.txt"));
//copy3(bis,bos);//缓冲流单字节拷贝
//copy4(bis, bos);//缓冲流数组拷贝
}
/**
* 缓冲流数组拷贝
* @param bis
* @param bos
* @throws IOException
*/
private static void copy4(BufferedInputStream bis, BufferedOutputStream bos) throws IOException {
byte[] bytes = new byte[1024];
int len;
while ((len= bis.read(bytes))!= -1){
bos.write(bytes,0,len);
}
bis.close();
bos.close();
}
/**
* 缓冲流单字节拷贝
* @param bis
* @param bos
* @throws IOException
*/
private static void copy3(BufferedInputStream bis, BufferedOutputStream bos) throws IOException {
int b ;
while ((b= bis.read())!=-1){
bos.write(b);
}
bis.close();
bos.close();
}
/**
* 字节流数组拷贝
* @param fis
* @param fos
* @throws IOException
*/
private static void copy2(FileInputStream fis, FileOutputStream fos) throws IOException {
byte[] bytes = new byte[1024];
int len;
while ((len= fis.read(bytes))!=-1){
fos.write(bytes,0,len);
}
fis.close();
fos.close();
}
/**
* 字节流单字节拷贝
* @param fis
* @param fos
* @throws IOException
*/
private static void copy1(FileInputStream fis, FileOutputStream fos) throws IOException {
int b;
while((b = fis.read())!=-1){
fos.write(b);
}
fis.close();
fos.close();
}
}