文件复制
public class Test4_Copy {
public static void main(String[] args) throws Exception {
// 1,创建读取文件和写出文件
File from = new File("D:\\teach\\a\\1.txt");
File to = new File("D:\\teach\\a\\to.txt");
//调用copy完成文件复制
copy(from, to);
}
//封装了文件复制的工具,将来可以通过类名.直接调用
public static void copy(File from, File to) throws Exception {
// 2,读取from,写出到to
InputStream in = new FileInputStream(from);
OutputStream out = new FileOutputStream(to);
// 3,开始读,读到-1为止
int b = 0;// 记录每次读取到的数据
while ((b = in.read()) != -1) {
out.write(b);// 把读到的内容写出去
}
// 4,关闭资源
in.close();
out.close();
}
}
批量读写
public class Test4_Copy {
public static void main(String[] args) throws Exception {
// 1,创建读取文件和写出文件
File from = new File("D:\\teach\\a\\1.txt");
File to = new File("D:\\teach\\a\\to.txt");
copyByte(from, to);// 一个字节一个自己的复制
copyArray(from, to);// 一个数组一个数组的复制
}
// 一个数组一个数组的复制
private static void copyArray(File from, File to) throws Exception {
// 2,读取from,写出到to
InputStream in = new FileInputStream(from);
OutputStream out = new FileOutputStream(to);
// 3,批量的读和写
int b = 0;// 记录每次读取到的数据
//源码:数组默认的长度一般是8M数组的长度就是8*1024
byte[] bs = new byte[8*1024];//用来缓存数据
while ((b = in.read(bs)) != -1) {//读取数组中的内容
out.write(bs);// 把读到的数组里的内容写出去
}
// 4,关闭资源
in.close();
out.close();
}
// 封装了文件复制的工具,将来可以通过类名.直接调用
public static void copyByte(File from, File to) throws Exception {
// 2,读取from,写出到to
InputStream in = new FileInputStream(from);
OutputStream out = new FileOutputStream(to);
// 3,开始读,读到-1为止
int b = 0;// 记录每次读取到的数据
while ((b = in.read()) != -1) {
out.write(b);// 把读到的内容写出去
}
// 4,关闭资源
in.close();
out.close();
}
}