package day2301;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class ZongHui {
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws IOException {
while (true) {
System.out.println("1:指定关键字检索文件 2:指定后缀名检索文件 3:复制/目录 4:退出");
int x = sc.nextInt();
switch (x) {
case 1:
GetFile();
break;
case 2:
GetFile2();
break;
case 3:
copyFile();
break;
case 4:
System.out.println("谢谢使用");
System.exit(0);
default:
System.out.println("输入错误,请重新输入。");
}
}
}
public static void copyFile() throws IOException {
System.out.println("请输入要复制的目录");
String str1 = sc.nextLine();
System.out.println("请输入目标位置:");
String str2 = sc.nextLine();
File src = new File(str1);
File dest = new File(str2);
if (!src.exists()) {
return;
}
dest = new File(dest, src.getName());
if (dest.exists()) {
dest.mkdirs();
}
Fuzhi(src, dest);
}
private static void Fuzhi(File src, File dest) throws IOException {
File[] arr = src.listFiles();
if (arr != null) {
for (File f : arr) {
if (f.isFile()) {
FileInputStream in = new FileInputStream(f);
FileOutputStream out = new FileOutputStream(new File(dest, f.getName()));
byte[] arrs = new byte[1024];
int len = 0;
while ((len = in.read(arrs)) != -1) {
out.write(arrs, 0, len);
// in.close();
// out.close();
}
} else if (f.isDirectory()) {
Fuzhi(f, dest);
}
}
}
}
public static void GetFile2() {
System.out.println("请输入要检索的目录位置:");
String str = sc.next();
System.out.println("请输入后缀名");
String key = sc.next();
File file = new File(str);
System.out.println("--------------------------");
listFile2(file, key);
}
private static void listFile2(File file, String key) {
if (!file.exists()) {
return;
}
File[] arr = file.listFiles();
if (arr != null) {
for (File f : arr) {
if (f.isFile()) {
if (f.getName().endsWith(key)) {
System.out.println(f.getAbsolutePath());
}
} else if (f.isDirectory()) {
listFile(f, key);
}
}
}
}
public static void GetFile() {
System.out.println("请输入要检索的目录位置:");
String str = sc.next();
System.out.println("请输要入搜索关键字");
String key = sc.next();
File file = new File(str);
System.out.println("--------------------------");
listFile(file, key);
}
private static void listFile(File file, String key) {
// if(!file.exists()){
// return;
// }
File[] arr = file.listFiles();
if (arr != null) {
for (File f : arr) {
if (f.isFile()) {
if (f.getName().contains(key)) {
System.out.println(f.getAbsolutePath());
}
} else if (f.isDirectory()) {
listFile(f, key);
}
}
}
}
}
|
|