CoreJava/exp10/CopyFile.java

68 lines
1.9 KiB
Java
Raw Normal View History

2024-05-09 09:10:51 +08:00
package exp10;
import java.io.*;
public class CopyFile {
public static void main(String[] args) {
String dirPath = "D:/MyProjects/CoreJava/exp10/MultiFile"; //源文件路径
String dstPath = "C:/test.java"; //目标文件路径
File dir = new File(dirPath);
File dst = new File(dstPath);
File[] files = dir.listFiles();
try{ //通过三种方式将源文件复制到目标文件中
charCopy(files[0], dst);
charArryCopy(files[1], dst);
bufferCopy(files[2], dst);
}catch(IOException e){
System.out.println("程序因为IO异常结束运行!");
}
}
//一次一个字节地读写
public static void charCopy(File src, File dst) throws IOException{
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst, true);
int b;
while ((b=in.read()) != -1){
out.write(b);
}
in.close();
out.close();
}
//一次一个季节数组地读写
public static void charArryCopy(File src, File dst) throws IOException{
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst, true);
byte[] buffer = new byte[1024];
int size;
while((size=in.read(buffer)) != -1){
out.write(buffer, 0, size);;
}
in.close();
out.close();
}
//缓冲字节流读写
public static void bufferCopy(File src, File dst) throws IOException{
BufferedInputStream in = new BufferedInputStream(new FileInputStream(src));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dst, true));
byte[] buffer = new byte[1024];
int size;
while((size=in.read(buffer)) != -1){
out.write(buffer, 0, size);;
}
out.flush();
in.close();
out.close();
}
}