关于文件的复制可分为:字节流和字符流,即二进制数据与文本文件(貌似文本也是二进制的吧),为什么要分呢?应该是主要考虑到效率的问题。。。

1、copy文本文件

1)简单字符流:

import java.io.*;
/**字符流复制文本文件
*/
public  class FileCharStreamDemo{
		public static void main(String[] args)throws Exception{
			
						FileReader fis  = new FileReader("e:/1.txt");
						FileWriter fos = new FileWriter("e:/10.txt");
						char[] buf = new char[1024];
						int len = 0;
						while((len = fis.read(buf))!= -1){
								fos.write(buf,0,len);
							}
						fos.close();//后打开的先关闭
						fis.close();//先打开的后关闭
			}
	}



2)、增强型(可提高效率)

import java.io.*;
/**字符流复制文本文件
*/
public  class FileCharStreamBufferedDemo{
		public static void main(String[] args)throws Exception{
			
						FileReader fis  = new FileReader("e:/1.txt");
						BufferedReader br = new BufferedReader(fis);
						
						FileWriter fos = new FileWriter("e:/10.txt");
						BufferedWriter bw = new BufferedWriter(fos);
						
						char[] buf = new char[1024];
						int len = 0;
						while((len = br.read(buf))!= -1){
								bw.write(buf,0,len);
							}
						bw.close();
						fos.close();//后打开的先关闭
						br.close();						
						fis.close();//先打开的后关闭
			}
	}

从上面的demo可以发现增强型就是在将原本的输入输出流上再套上一层,这样想想管道就可以很明白了,本来是一根直径5cm的管,在不允许换管的情况下,为其套上一个直径10cm的管,就可以缓解接口的压力,因为大部分压力在中间被抵消了。so 。。。。。。。。。。

2、二进制文件的复制

1)原生的复制:

import java.io.*;
/**字节流复制文件
*/
public  class FileByteStreamDemo{
		public static void main(String[] args)throws Exception{
			
						FileInputStream fis  = new FileInputStream("e:/1.txt");
						FileOutputStream fos = new FileOutputStream("e:/10.txt");
						byte[] buf = new byte[1024];//可自定义缓冲区大小
						int len = 0;
						while((len = fis.read(buf))!= -1){
								fos.write(buf,0,len);
							}
						fos.close();//后打开的先关闭
						fis.close();//先打开的后关闭
			}
	}

其实,这个也可以作用于文本文件,效率略低而已。

2)对应于字符流,二进制当然也有增强效率的类

import java.io.*;
/**字节流复制文件
*/
public  class FileByteStreamBufferedDemo{
		public static void main(String[] args)throws Exception{
			
						FileInputStream fis  = new FileInputStream("e:/1.txt");						
						BufferedInputStream bis = new BufferedInputStream(fis);
						FileOutputStream fos = new FileOutputStream("e:/10.txt");
						BufferedOutputStream bos = new BufferedOutputStream(fos);
						
						byte[] buf = new byte[1024];
						int len = 0;
						while((len = bis.read(buf))!= -1){
								bos.write(buf,0,len);
							}
						bos.close();
						fos.close();//后打开的先关闭
						bis.close();//先打开的后关闭
						fis.close();
						
			}
	}

下午,看api的时候还发现FileInputStream提供了一个方法getchannel(),当copy大文件时,建议用这个,代码如下:

import java.io.*;
import java.nio.channels.*; 

public class FileChannelDemo{
		public static void main(String[] args)throws Exception{
					
					FileChannel  in = new FileInputStream("e:/1.exe").getChannel();
					FileChannel  out = new FileOutputStream("f:/qq.exe").getChannel();
					in.transferTo(0,in.size(),out);
					out.close();
					in.close();
			}
	}