文件操作

package com.june;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Client {
    public static Map<String, File> STU_FILES = new HashMap<String, File>();
    public static List<String> STU_RS = new ArrayList<String>();

    public static void main(String[] args) throws Exception {
        findBooksByName("XX");
    }

    public static List<String> findBooksByName(String stuName) throws Exception {
        STU_RS = new ArrayList<String>();
        STU_FILES = new HashMap<String, File>(); 
        String path = "D:/mySVN";
        findAllFiles(new File(path), stuName);
        dealFiles(stuName);
        return STU_RS;
    }

    public static void findAllFiles(File f, String stuName) {
        if (f.isFile()) {
            if (f.getAbsolutePath().contains(stuName)) {
                STU_FILES.put(toNewPath(f), f);
            }
        } else {
            File[] fs = f.listFiles();
            for (File tempFile : fs) {
                findAllFiles(tempFile, stuName);
            }
        }
    }

    public static String toNewPath(File file) {
        String fileName = file.getParent().substring(file.getParent().lastIndexOf("\\") + 1) + "-"
                + file.getName().substring(file.getName().lastIndexOf("_") + 1);
        return fileName;
    }

    public static void dealFiles(String stuName) throws Exception {
        // 1、构建文件的目录
        String filePath = "d:/stuBooks/" + stuName + "/";
        File dir = new File(filePath);
        dir.mkdirs();
        // 清除目录的文件
        File[] fs = dir.listFiles();
        for (File f : fs) {
            f.delete();
        }
        Set<String> keys = STU_FILES.keySet();
        Iterator<String> it = keys.iterator();
        while (it.hasNext()) {
            String key = it.next();
            File tempFile = STU_FILES.get(key);
            // 构建文件名
            String fileName = toNewPath(tempFile);
            String fileWholeName = filePath + fileName;
            fileCopy(tempFile, new File(fileWholeName));
            System.out.println(fileWholeName);
            STU_RS.add(fileWholeName);
        }
    }

    public static void fileCopy(File sourceFile, File targetFile) {
        try {
            Files.copy(sourceFile.toPath(), targetFile.toPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值