第14周作业

 

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

package com;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;

public class A {
	public static void main(String[] args) {
		Scanner reader = new Scanner(System.in);
		System.out.print("请输入目录");
		String path = reader.nextLine();
		File f = new File(path);
		String[] filenames = f.list();
		System.out.print("该目录的文件为" + "\n");

		for (int i = 0; i < filenames.length; i++) {
			System.out.print(filenames[i] + "\n");
		}
		System.out.print("请输入你想查找文件的类型:");
		X1 typefile = new X1(reader.nextLine());
		String[] filenames1 = f.list(typefile);
		System.out.print("此类型文件为");
		for (int i = 0; i < filenames1.length; i++) {
			System.out.print(filenames1[i] + "\n");
		}
		System.out.print("请输入需要剪切的文件名:\n");
		String cut = reader.nextLine();
		File cutfile = new File(path + "\\" + cut);
		System.out.print("请输入该文件需要移动到的目录:\n");
		String cutpath = reader.nextLine();

		File file1 = new File(cutpath);
		file1 = cutfile;
		File file2 = new File(cutpath + "\\" + cut);

		// 在程序结束时删除文件1
		file1.deleteOnExit();
		try {

			file2.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		cutFile(file1, file2);
	}

	public static void cutFile(File file1, File file2) {
		FileOutputStream fileOutputStream = null;
		InputStream inputStream = null;
		byte[] bytes = new byte[1024];
		int temp = 0;
		try {
			inputStream = new FileInputStream(file1);
			fileOutputStream = new FileOutputStream(file2);
			while ((temp = inputStream.read(bytes)) != -1) {
				fileOutputStream.write(bytes, 0, temp);
				fileOutputStream.flush();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fileOutputStream != null) {
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}
}

class X1 implements FilenameFilter {
	String type;

	X1(String type) {
		this.type = type;
	}

	public boolean accept(File file, String name) {
		return name.endsWith(type);
	}
}

  

 

 

 

 

 

 

 

posted @ 2019-12-08 21:18  子兢  阅读(107)  评论(0编辑  收藏  举报