JAVA文件IO流,递归,File数组
习题练习1:
控制台输入目录名以及敏感词汇,程序自动检索该目录下所有文件内容是否存在敏感词汇,存在,则将文件复制到指定文件夹中;
本题主要考察File数组的使用,递归方法,以及文件输入输出字节流的使用(FileInputStream、FileOutputStream)
public class WorkTwo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入一个正确的文件加地址");
String str = input.nextLine();
System.out.println("请输入需要查找的敏感字");
String sensitive = input.nextLine();
System.out.println("请输入要转移文件的新文件夹地址");
String newFiles = input.nextLine();
//调用静态test方法
test( str,sensitive,newFiles);
}
// 创建一个静态方法,参数是一个目录地址,敏感字字符串,和一个转移文件夹地址
public static void test(String str, String sensitive, String newFiles) {
// 创建一个文件对象
File file = new File(str);
File file1 = new File(newFiles);
//判断该文件夹是否存在
if (!file.exists()) {
System.out.println("该路径下的文件或文件夹不存在");
}
//创建一个File对象数组
File[] files = file.listFiles();
//遍历数组
for (int i = 0; i < files.length; i++) {
// 判断是否为文件夹
if (files[i].isDirectory()) {
// 获得当前文件夹的绝对路径
String path = files[i].getAbsolutePath();
// 自己调用自己的方法,重新创建一个File对象数组,继续遍历
test(path, sensitive, newFiles);
} else {
//利用String类的indexOf方法判断文件名字是否有敏感字,有的话返回正确的下标位置
//没有则返回-1,这样我们可以利用这个特性来简介判断文件名字是否够有该敏感字
int num = files[i].getName().indexOf(sensitive);
// 如果返回的下标位置为-1,则表示不存在敏感字
FileInputStream fis = null;
FileOutputStream fos = null;
if (num != (-1)) {
try {
//创建一个文件输入流对象,参数为当前文件的绝对地址
fis = new FileInputStream(files[i].getAbsolutePath());
//创建一个文件输出流对象
fos = new FileOutputStream(new File(newFiles + "\\" + files[i].getName()));
//len为每次读取的有效字节个数
int len = 0;
//创建一个Byte数组
byte[] bytes = new byte[1024];
//当len为-1时,则代表当前对象的信息已经全部读取完毕
while ((len = fis.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
}
}