java文件操作工具类(四)
try {
InputStream is = new FileInputStream(source); // 用于读取文件的原始字节流
OutputStream os = new FileOutputStream(tarpath); // 用于写入文件的原始字节的流
byte[] buf = new byte[1024];// 存储读取数据的缓冲区大小
int len = 0;
while ((len = is.read(buf)) != -1) {
os.write(buf, 0, len);
}
is.close();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* @param args
*/
/*
* copy这个方法主要是用来实现文件上传的,实现的原理就是分别打开输入输出流,进行文件拷贝的
*/
public void copyFile(File src, File dist) {
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dist),
BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
int len = 0;
try {
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}