IO流练习题

记录一下IO流的练习题

读进来(input),写出去(output)

1.递归复制文件夹及文件

2.获取文本上字符出现的次数,把数据写入文件

3.列出file目录的下级,如果它的下级还是目录,接着列出下级的下级,依次类推

4.求任意一个目录的总大小


public class FileTest {

    /**
     * 1.递归复制文件夹及文件
     * <p>
     * <p>
     * 思路:
     * 1.判断源文件是目录还是文件
     * 2.是目录,判断目标文件是否存在,不存在则直接创建
     * 3.获取源文件下的所有子集目录,循环遍历子集目录,递归调用方法复制
     * 4.是文件,创建文件字节缓冲输入输出流,创建一个字节数组,读取的数据放缓冲区
     * 5.循环把读到的数据写入到文件中
     * 6.关闭资源
     *
     * @param src  源文件
     * @param dest 目标文件
     * @throws IOException
     */
    public static void copyFiles(String src, String dest) throws IOException {

        File srcFile = new File(src);//源文件

        if (srcFile.isDirectory()) { //目录
            File destFile = new File(dest);//目标文件

            if (!destFile.exists()) {//目标不存在直接创建
                destFile.mkdirs();

                File[] listFiles = srcFile.listFiles();//返回该文件下的子集目录
                for (File file : listFiles) {
                    //递归调用
                    copyFiles(file.toString(), dest + "/" + file.getName());
                }


            }
        } else {//文件
            BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(src)); //源文件

            BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(dest));//目标文件

            byte[] buffer = new byte[1024 * 10];//读取的数据放缓冲区
            int len = 0;//标记一下读到了哪里

            while ((len = inputStream.read(buffer)) != -1) {// -1表示读到了文件末尾
                outputStream.write(buffer, 0, len);//从0开始写buffer数据,写到len
                outputStream.flush();
            }

            //关闭资源
            inputStream.close();
            outputStream.close();

        }

    }

    /**
     * 2.获取文本上字符出现的次数,把数据写入文件
     * <p>
     * 思路:
     * 1.遍历文本每一个字符
     * 2.字符出现的次数存在Map中
     * <p>
     * Map<Character,Integer> map = new HashMap<Character,Integer>();
     * map.put('a',18);
     * map.put('你',2);
     * <p>
     * 3.把map中的数据写入文件
     *
     * @param fileName 要统计的文件
     * @param outFile  把统计的文件输出的文件
     */
    public static void wordCount(String fileName, String outFile) {

        BufferedReader bufferedReader = null;
        BufferedWriter bufferedWriter = null;
        try {
            bufferedReader = new BufferedReader(new FileReader(fileName));
            bufferedWriter = new BufferedWriter(new FileWriter(outFile));


            //1.创建Map集合
            Map<Character, Integer> map = new HashMap<Character, Integer>();

            //2.遍历每一个字符,每一个字符出现的次数放到map中
            int c = 0;
            while ((c = bufferedReader.read()) != -1) {
                //int 还原 char
                char ch = (char) c;
                // 判断char是否在map中第一次出现
                if (map.get(ch) == null) {
                    map.put(ch, 1);
                } else {
                    map.put(ch, map.get(ch) + 1);
                }
            }

            //3.遍历map,再写入数据
            Set<Map.Entry<Character, Integer>> entries = map.entrySet();
            for (Map.Entry<Character, Integer> entry : entries) {
                switch (entry.getKey()) {
                    case ' ':
                        bufferedWriter.write("空格:" + entry.getValue());
                        break;
                    case '\t':
                        bufferedWriter.write("tab键=" + entry.getValue());
                        break;
                    case '\r':
                        bufferedWriter.write("回车=" + entry.getValue());
                        break;
                    case '\n':
                        bufferedWriter.write("换行=" + entry.getValue());
                        break;
                    default:
                        bufferedWriter.write(entry.getKey() + "=" + entry.getValue());
                        break;
                }
                bufferedWriter.newLine();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关流
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }


    }


    /**
     * 3.列出file目录的下级,如果它的下级还是目录,接着列出下级的下级,依次类推
     *
     * @param file
     */
    public static void listAllSubFiles(File file) {

        if (file.isFile()) {
            System.out.println(file);

        } else {
            File[] listFiles = file.listFiles();

            for (File fileAll : listFiles) {
                // 如果all[i]是文件,直接打印
                // 如果all[i]是目录,接着再获取它的下一级
                listAllSubFiles(fileAll);
            }
        }
    }


    /**
     * 4.求任意一个目录的总大小
     *
     * @param file
     * @return 目录的总大小
     */
    public long getDirectorySize(File file) {

        // file是文件,那么直接返回file.length()
        // file是目录,把它的下一级的所有大小加起来就是它的总大小
        long size = 0;

        if (file.isFile()) {
            size += file.length();

        } else {
            File[] listFiles = file.listFiles();// 获取file的下一级
            // 累加all[i]的大小
            for (File files : listFiles) {
                size += getDirectorySize(files);
            }
        }

        return size;

    }

    /**
     * 5.删除指定目录
     *
     * @param file
     */
    public void deleteDirectory(File file) {
        // 如果file是文件,直接delete
        // 如果file是目录,先把它的下一级干掉,然后删除自己

        if (file.isDirectory()) {
            File[] listFiles = file.listFiles();

            // 循环删除的是file的下一级
            for (File files : listFiles) {
                deleteDirectory(file);
            }
        }

        file.delete();
    }


}

递归复制指定目录下指定后缀的文件

/**
 * 你想从N层文件夹内复制出你想要的格式文件时,只需要指定目录即可完成复制
 * @author admin
 *
 */
public class Demo {
	public static void main(String[] args) throws IOException {
//		String srcFolder = "F:\\BaiduNetdiskDownload\\4.Linux运维学科--Linux服务管理";
//		String destFolder = "F:\\BaiduNetdiskDownload\\4.Linux运维学科--Linux服务管理\\pdf";
//
// 
//		File srcFolder11 = new File(srcFolder);
//		File destFolder11 = new File(destFolder);
// 
//		copyFile(srcFolder11, destFolder11);
		String file = "F:\\BaiduNetdiskDownload\\4.Linux运维学科--Linux服务管理";
		deleteFile(new File(file));
		System.out.println("************************");
		System.out.println("ok");
 
	}
	
	/**
	 * 递归删除指定目录下后缀的文件
	 * @param srcFolder 指定文件夹
	 * @throws IOException
	 */
	private static void deleteFile(File srcFolder) throws IOException {
		if (srcFolder.isDirectory()) {
			File[] fileArrays = srcFolder.listFiles();
			for (File file : fileArrays) {//是文件夹就递归
				if (file.isDirectory()) {
					deleteFile(file);
				} else {

					if (file.getName().endsWith(".avi")) {//指定后缀
						file.delete();
					}
 
				}
			}
		}
	}
	
	
 /**
  * 递归复制指定目录下指定后缀的文件
  * @param srcFolder 原目录
  * @param destFolder 复制到目录
  * @throws IOException
  */
	private static void copyFile(File srcFolder, File destFolder) throws IOException {
		if (srcFolder.isDirectory()) {
			File[] fileArrays = srcFolder.listFiles();
			for (File file : fileArrays) {//是文件夹就递归
				if (file.isDirectory()) {
					copyFile(file, destFolder);
				} else {

					if (file.getName().endsWith(".pdf")) {//指定后缀
						File newFile = new File(destFolder, file.getName());
						newFile.createNewFile();
						copy(file, newFile);
					}
 
				}
			}
		}
	}
 
	/**
	 * 复制文件
	 * @param file
	 * @param newFile
	 * @throws IOException
	 */
	private static void copy(File file, File newFile) throws IOException {
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));
 
		byte[] bys = new byte[1024];
		int len = 0;
		while ((len = bis.read(bys)) != -1) {
			bos.write(bys, 0, len);
		}
		bos.close();
		bis.close();
	}

}
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值