题目:
编写一个应用程序,输入一个目录和一个文件类型,显示该目录下符合该类型的所有文件。之后,将这些文件中的某一个文件剪切到另外一个目录中。
代码:
import java.io.*; import java.util.Scanner; class FileAccepct implements FilenameFilter{ String str = null; FileAccepct(String str){ this.str = "."+str; } public boolean accept(File dir, String name) { return name.endsWith(str); } } public class test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("请输入一个目录和一个文件类型"); Scanner s=new Scanner(System.in); String path=s.next(); File dir =new File(path); FileAccepct f =new FileAccepct(s.next()); String list[]=dir.list(f); for(int i = 0;i<list.length;i++){ System.out.print(list[i]+" "); } System.out.println("请输入需要剪切的文件名:"); String cut = s.next(); File cutfile = new File(path+"\"+cut); System.out.println("请输入该文件需要移动到的目录:"); String cutway = s.next(); File cutlist = new File(cutway); File newfile = new File(cutway+"\"+cut); try { newfile.createNewFile();//创建新文件 } catch (IOException e) { e.printStackTrace(); } InputStream inputStream = null; BufferedInputStream bufferedInputStream = null; String filedata=""; Writer writer = null; BufferedWriter bufferedWriter = null; try { inputStream = new FileInputStream(cutfile); bufferedInputStream = new BufferedInputStream(inputStream); byte[] b = new byte[1024]; int count = 0; while((count = bufferedInputStream.read(b, 0, 1024))!=-1){ filedata=filedata+new String(b, 0, count); } writer = new FileWriter(newfile); bufferedWriter = new BufferedWriter(writer); bufferedWriter.write(filedata); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { bufferedInputStream.close(); inputStream.close(); bufferedWriter.close(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } cutfile.delete(); } }
运行