题目:编写一个应用程序,输入一个目录和一个文件类型,显示该目录下符合该类型的所有文件。
import java.io.File; import java.io.FilenameFilter; public class text implements FilenameFilter{ String type; text(String type){ this.type=type; } public text() { // TODO Auto-generated constructor stub } @Override public boolean accept(File file, String name) { // TODO Auto-generate method stub return name.endsWith(type);
import java.io.BufferedInputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.util.Scanner; public class FileText { public static void main(String[] args) { File file=new File("C:\\Java"); FilenameFilter fn=new text("docx"); String[] names=file.list(fn); File[] fr=file.listFiles(); for(int i=0;i<fr.length;i++){ System.out.println("目录下下的文件"+fr[i]); } for(int i=0;i<names.length;i++){ System.out.println("有DOCX后缀 的文件"+names[i]); } } }
}
}
之后,将这些文件中的某一个文件剪切到另外一个目录中。
import java.io.BufferedInputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.util.Scanner; public class file { public static void main(String[] args) { Scanner reader = new Scanner(System.in); System.out.print("请输入目录:\n"); String way = reader.nextLine(); File file = new File(way); System.out.print("请输入需要剪切的文件名:\n"); String cut = reader.nextLine(); File cutfile = new File(cut); System.out.print("请输入该文件需要移动到的目录:\n"); String cutway = reader.nextLine(); File cutlist = new File(cutway); File newfile = new File(cutway); try { newfile.createNewFile();//创建同名文件 } catch (IOException e) { e.printStackTrace(); } InputStream inputStream = null;//读出原文件内容对象创建 BufferedInputStream bufferedInputStream = null; String data="";//内容暂存器 Writer writer = null;//写入新文件内容对象创建 BufferedWriter bufferedWriter = null; try { inputStream = new FileInputStream(cutfile); bufferedInputStream = new BufferedInputStream(inputStream); byte[] content = new byte[1024];//存储内容 int count = 0;//记录长度 while((count = bufferedInputStream.read(content, 0, 1024))!=-1){ data=data+new String(content, 0, count);//遍历到字节存入字符串 } writer = new FileWriter(newfile); bufferedWriter = new BufferedWriter(writer); bufferedWriter.write(data);//字符串写入新文件 } 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();//删除原文件 } }