public class FileUtil {
/**
* 利用缓冲流复制文件
* @param from源文件
* @param to目标文件
*/
public static boolean bufCopy(String from,String to) {
//InputStream是所有出输入流的父类
InputStream in = null;
//OutputStream是所有输出流的父类
OutputStream out = null;
try {
in = new BufferedInputStream(
new FileInputStream(from));
out = new BufferedOutputStream(
new FileOutputStream(to));
//读取数据的int类型,第八位有效,若为-1则表示文件读取结束
int temp;
while ((temp = in.read()) != -1) {
//不直接写文件,将数据写入缓冲数组中
//在流关闭、缓冲数组饱和,会写入文件并清理缓冲数组
out.write(temp);
}
System.out.println("OK");
return true;
} catch (FileNotFoundException e1) {
String msg = e1.getMessage();
System.out.println(msg+":文件不存在!");
return false;
} catch (IOException e2) {
System.out.println("文件读写错误:"+e2);
return false;
} finally {
if (in != null ) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null ) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 利用缓冲区复制文件
* @param src源文件
* @param dst目标文件
* @throws CopyException自定义读写异常
*/
public static void Copy(String src,String dst) throws CopyException{
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(src);
out = new FileOutputStream(dst);
//定义缓冲区,临时存放读取数据
byte[] data = new byte[8*1024];
//返回有效数据长度
int temp;
while ((temp = in.read(data)) != -1) {
//按有效长度,将临时数组数据写入文件中
out.write(data,0,temp);
}
System.out.println("OK");
} catch (FileNotFoundException e1) {
throw new CopyException("文件不存在!",e1);
} catch (IOException e2) {
throw new CopyException("文件读写错误!",e2);
} finally {
if (in != null ) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null ) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
/**
* 自定义读写异常
* @author Administrator
*
*/
class CopyException extends Exception{
public CopyException() {
super();
// TODO Auto-generated constructor stub
}
public CopyException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public CopyException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public CopyException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
}
文件读取方案:
*方案一、直接使用FileInputStream,逐个字节读写(效率最低);
方案二、自定义byte数组,作为临时数据存储区域,批量读写数据;
方案三、利用缓冲流(过滤流)管理缓冲区,每次还是读取一个byte。*
缓冲流:在其他流的基础上拓展功能,扩充缓冲区,提高工作效率。