文件複製
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();
}
}