第14周作业
题目:
编写一个应用程序,输入一个目录和一个文件类型,显示该目录下符合该类型的所有文件。之后,将这些文件中的某一个文件剪切到另外一个目录中。
代码:
1、Select类
class Select implements FilenameFilter{
String type;
Select(String type){
this.type=type;
}
public boolean accept(File dir, String name) {
return name.endsWith(type);
}
}
2、主类
import java.util.*;
import java.io.*;
public class test {
public static void main(String[] args) throws IOException {
//查找指定目录下的全部文件
System.out.println("请输入要查询的目录:");
Scanner r=new Scanner(System.in);
String SearchDir=r.nextLine();
File f=new File(SearchDir);
String[] AllFiles=f.list();
for(String a:AllFiles){
System.out.println(a);
}
//筛选当前目录下,指定类型的文件
System.out.println();
System.out.println("请输入要筛选的文件类型:");
String type=r.nextLine();//接收输入的文件类型
Select s=new Select(type);
String[] SelFiles=f.list(s);
for(String a:SelFiles){
System.out.println(a);
}
//剪切操作
System.out.println();
System.out.println("请输入需要剪切的文件名:");
String name=r.nextLine();
File CutFile=new File(SearchDir,name);//此对象是原目录下的原文件
System.out.println("请输入剪切到的目录:");
String NewPath=r.nextLine();//接收新路径
File NewFile=new File(NewPath,name);//此对象是新目录下的同名新文件
try {
NewFile.createNewFile();//通过方法,创建一个新的文件
} catch (IOException e) {
e.printStackTrace();
}
BufferedInputStream bin=null;
BufferedWriter bw=null;
int count=0;
byte[]b=new byte[1024];
try {
bin=new BufferedInputStream(new FileInputStream(CutFile));
String str="";//接收原文件中的内容
while((count=bin.read(b,0,1024))!=-1){
str=str+new String(b);
}
bw=new BufferedWriter(new FileWriter(NewFile,true));
bw.write(str);//将接收的内容写入新文件中
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
bin.close();
bw.close();
}
CutFile.delete();//删除源文件
}
}
运行结果:
1、所查询目录的初始状态

2、目标目录的初始状态

3、程序运行结果

4、程序运行后,目标目录状态

5、原目录的状态


浙公网安备 33010602011771号