Java基础-FileInputStream与FileOutputStream
Java基础-FileInputStream与FileOutputStream
利用FileInputStream与FileOutputStream写一个文件复制的工具类
Demo
import java.io.*;
public class FileCope{
/*
* path为需要复制文件的地址
* paths为复制后文件输出的地址
*/
public static void cope(String path,String paths) throws IOException{
FileInputStream in = null;
File file = null;
FileOutputStream out = null;
try {
in = new FileInputStream(path);
file = new File(paths);
if (!file.exists()) {
file.createNewFile();//创建文件
}
out = new FileOutputStream(file);
int c;
byte[] buffer = new byte[1024];
/*
* Java中api文档java.io中有read()方法的解释
* read(byte[] b) 从此输入流中将 b.length个字节的数据读入一个 byte[] b数组中。
* 使用read(byte[] b)效率更高,只需读(文件大小(单位byte)/b.length)次。
* 如果因为已经到达流末尾而没有更多的数据,则返回 -1。
*/
while ((c = in.read(buffer)) != -1) {
for (int i = 0; i < c; i++) {
out.write(buffer[i]);
}
}
System.out.println("文件复制success!path:"+path+" paths:"+paths);
} catch (Exception e) {
System.out.println("复制文件error!path:"+path+" paths:"+paths);
throw e;
} finally {
/*
* 最后一定要将输入、输出流关闭,释放系统资源
*/
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
最后附上Java中api文档java.io中read()方法的解释