图书整理系统(2)--对图书名称进行清洗

由于历史遗留数据,网上下载的书籍很多情况下会带有下载网站等地址信息,以及“高清”“扫描版”“最新版”等字段,因此需要将文件名进行清洗,以保证后续处理可以匹配到相应的数据。

分为以下步骤:

1.获取路径下所有书籍

2.对书籍名称与原书籍名称进行清洗

3.如果新书籍名和原来书籍名称不相等,就对书籍进行重命名

代码如下

 package com.gugu.book;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class CleanFileName {
    
    static String basePath = "E:\\File\\培训\\book";
    
    public static void main(String[] args) {
        List<String> fileNameList = getAllFile(basePath, false);
        dealWith(fileNameList);
    }
    
    /**
     * @param allFile
     */
    private static void dealWith(List<String> fileNameList) {
        for (String oldFileName : fileNameList) {
            String newFileName = oldFileName.replace("[", "")
                .replace("]", "")
                .replace("(", "(")
                .replace(")", ")")
                .replace("《", "")
                .replace("》", "")
                .replace("+", " ")
                .replace("---", " ")
                .replace("(带书签)", " ")
                .replace("..", ".")
                .replace(".扫描版", "")
                .replace("(jb51.net)", "")
                .replace("@jb51.net", "")
                .replace(".PDF", ".pdf")
                .replace("——", "");
            if(!newFileName.equals(oldFileName) ){
                renameFile(oldFileName, newFileName);
            }
            
        }
    }

    public static List<String> getAllFile(String directoryPath,boolean isAddDirectory) {
        List<String> list = new ArrayList<String>();
        File baseFile = new File(directoryPath);
        if (baseFile.isFile() || !baseFile.exists()) {
            return list;
        }
        File[] files = baseFile.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                if(isAddDirectory){
                    list.add(file.getAbsolutePath());
                }
                list.addAll(getAllFile(file.getAbsolutePath(),isAddDirectory));
            } else {
                list.add(file.getAbsolutePath());
            }
        }
        return list;
    }
    
    /**文件重命名 
     * @param oldname  原来的文件名 
     * @param newname 新文件名 
     */ 
     public static void renameFile(String oldname,String newname){ 
         if(!oldname.equals(newname)){//新的文件名和以前文件名不同时,才有必要进行重命名 
             File oldfile=new File(oldname); 
             File newfile=new File(newname); 
             if(!oldfile.exists()){
                 return;//重命名文件不存在
             }
             if(newfile.exists())//若在该目录下已经有一个文件和新文件名相同,则不允许重命名 
                 System.out.println(newname+"已经存在!"); 
             else{ 
                 oldfile.renameTo(newfile); 
             } 
         }else{
             System.out.println("新文件名和旧文件名相同...");
         }
     }
}

猜你喜欢

转载自blog.csdn.net/zhazhagu/article/details/80885743