复制目录或文件以及生成临时目录或文件

来源:互联网 发布:电动自行车 知乎 编辑:程序博客网 时间:2024/05/21 11:19
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;


public class Text {


public static void main(String[] args) throws IOException {
// 复制文件
// 注释部分为把所有文件前加上时间
// 本程序中,临时文件是新建现在时间的文件夹
Date date = new Date();
SimpleDateFormat dat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-");
String ss = dat.format(date.getTime());
Scanner z = new Scanner(System.in);
System.out.println("请输入你想要复制的文件或者目录(全路径名)");
String s1 = z.next();
File f1 = new File(s1);
if (!f1.exists()) {
System.out.println("文件名有误或者文件不存在");
return;
}
System.out.println("请输入要复制到的位置(全路径名)");
String s2 = z.next();
System.out.println("临时文件是保存到新建现在时间的文件夹中");
System.out.println("是否生成临时文件?否(1)");
int s4 = z.nextInt();
if (s4 == 1) {
if (new File(s2 + s1.substring(s1.lastIndexOf("\\"))).exists()) {
if (f1.isDirectory()) {
System.out.println("是否合并目录且覆盖相同名称的文件?是(1)");
int s3 = z.nextInt();
if (s3 != 1) {
s2 = s2 + "\\" + ss;
File f = new File(s2);
f.mkdir();
}
} else {
System.out.println("是否覆盖原文件?是(1)");
int s3 = z.nextInt();
if (s3 != 1) {
s2 = s2 + "\\" + ss;
File f = new File(s2);
f.mkdir();
}
}
}
} else {
s2 = s2 + "\\" + ss;
File f = new File(s2);
f.mkdir();
}
Text f = new Text();
f.pd(f1, s2, s1.lastIndexOf("\\"));
}


public void pd(File file, String str, int a) throws IOException {
// Date date = new Date();
// SimpleDateFormat dat=new SimpleDateFormat("yyyy_MM_dd");
// String ss=dat.format(date.getTime());
// String s = file.getAbsolutePath();
// a=s.lastIndexOf("\\");
// s=s.substring(a+1);
// System.out.println(s);
// s=str+"\\"+ss+s;
String s = file.getAbsolutePath();
s = s.substring(a);
System.out.println(s);
s = str + s;
if (file.isDirectory()) {
File f = new File(s);
f.mkdir();
// String st=s;
// int d=a;
File[] c = file.listFiles();
for (File fil : c) {
// pd(fil,st,d);
pd(fil, str, a);
}
} else {
FileInputStream put = new FileInputStream(file.getAbsolutePath());
int len = put.available();
byte[] by = new byte[len];
put.read(by);
FileOutputStream out2 = new FileOutputStream(new File(s));
out2.write(by);
// put.close();
out2.close();
System.out.println(file);
}
}
}
0 0
原创粉丝点击