迟到的第14周作业

题目:编写一个应用程序,输入一个目录和一个文件类型,显示该目录下符合该类型的所有文件。之后,将这些文件中的某一个文件剪切到另外一个目录中。

代码:

package factorial;
import java.io.*;

/**
 * 
 * @ClassName:  ReadAndWrite  
 * @author Dandelion_Rain
 * @date:   2019年12月6日 下午6:10:39
 * 编写一个应用程序,输入一个目录和一个文件类型,显示该目录下符合该类
 * 型的所有文件。之后,将这些文件中的某一个文件剪切到另外一个目录中。
 */
public class ReadAndWrite {

    public static void main(String[] args) {
        File test = new File("E:\\A");
        FileAccept accept = new FileAccept("txt"); //选取类型
        String[] name = test.list(accept); //获取目录下accept的文件类型,以字符串方式储存
        //遍历
        for(String testname : name) {
            System.out.println(testname);
        }
        /**
         * 剪切到另一个文件夹:
         * 1.打开新的文件夹
         * 2.读取->放到字符串中->关闭读取->写入(以追加方式)-> 关闭写入->删除文件
         */
        File Reader = new File("E:\\A\\3.txt");
        FileInputStream input = null;
        BufferedInputStream buffereadinput = null;
        File writer = new File("D:\\3.txt");
        Writer output = null;
        BufferedWriter buffereadoutput = null;
        try {
            //读取
            input = new FileInputStream(Reader);
            buffereadinput = new BufferedInputStream(input);
            StringBuffer arrayinput = new StringBuffer();
            byte[]   inputfile = new byte[1024];
            int count = 0;
            while((count = buffereadinput.read(inputfile, 0,1024) )!=-1) {
                arrayinput.append(new String(inputfile,0,count,"UTF-8")); //以UTF-8编码格式输出(中文)
            }
            //System.out.println(arrayinput);
            
            //写入
            writer.createNewFile(); //创建文件
            output = new FileWriter(writer,true);//追加
            buffereadoutput = new BufferedWriter(output);
            String outWriter = arrayinput.toString();
            buffereadoutput.write(outWriter);
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                //关闭
                buffereadinput.close();
                input.close();
                buffereadoutput.close();
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            
        }
        //删除
        Reader.delete();    
    }

}

//筛选器
class FileAccept implements FilenameFilter{

    String type;
    FileAccept(String type){
        this.type = type;
    }
    public boolean accept(File dir, String name) {
        return name.endsWith(type);
    }
    
}

 

运行结果:

posted on 2019-12-06 20:16  李基民  阅读(149)  评论(0编辑  收藏  举报