import java.io.*;
import java.util.Scanner;
public class cp {
public static void copyFolder(File fileold , File filenew) {
if(fileold.isDirectory()){
File temp=new File(filenew,fileold.getName());
temp.mkdirs();
for (File file : fileold.listFiles()) {
copyFolder(file,temp);
}
}else{
copyFile(fileold,new File(filenew,fileold.getName()));
}
}
public static void copyFile(File strOldpath, File strNewPath) {
InputStream inputStream =null;
FileOutputStream fileOutputStream =null;
try {
// File fOldFile = new File(strOldpath);
if (strOldpath.exists()) {
int bytesum = 0;
int byteread = 0;
inputStream = new FileInputStream(strOldpath);
fileOutputStream = new FileOutputStream(strNewPath);
byte[] buffer = new byte[1024];
while ((byteread = inputStream.read(buffer)) != -1) {
bytesum += byteread; //这一行是记录文件大小的,可以删去
fileOutputStream.write(buffer, 0, byteread);
//三个参数,第一个参数是写的内容,
//第二个参数是从什么地方开始写,第三个参数是需要写的大小
}
// inputStream.close();
// fileOutputStream.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("复制单个文件出错");
e.printStackTrace();
}finally {
if(inputStream!=null)
{
try{
inputStream.close();
}catch (IOException e2)
{
e2.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e3) {
e3.printStackTrace();
}
}
}
}
public static void main(String args[]) {
Scanner input=new Scanner(System.in);
System.out.println("请输入旧的路径:");
String oldpath = input.next();
File f1 = new File(oldpath);
System.out.println("请输入新的路径");
String newpath = input.next();
File f2 = new File(newpath);
copyFolder(f1,f2);
}
}
java 实现Linux中的cp命令
最新推荐文章于 2023-02-02 14:25:53 发布
本文提供了一个使用Java实现的文件及文件夹复制程序示例。该程序通过递归方式复制目录及其所有子文件和子目录到指定的目标位置,并详细展示了如何处理文件读取和写入过程中的异常。

914

被折叠的 条评论
为什么被折叠?



