java文件和目录操作FileUtil

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Component
public class FileUtil {

  private static final String PATH_SEPARATOR = System.getProperty("file.separator");

  private static final String BACKUP_NAME = "backup";

  private static int MAX_FILES_COUNT;

  //@Value cannot set value to static fields, just use the following method to bypass this restriction
  @Value("${backup.maxfiles}")
  public void setMaxFilesCount(int c) {
    MAX_FILES_COUNT = c;
  }

  /**
   * 读取文件内容
   *
   * @param fileName
   * @return
   * @throws IOException
   */
  public static String readJsonFile(String fileName) throws IOException {
    String jsonStr = "";
    File jsonFile = new File(fileName);
    return readJsonFile(jsonFile);
  }

  public static String readJsonFile(File jsonFile) throws IOException {
    String jsonStr = "";
    if (!jsonFile.exists()) {
      return jsonStr;
    }
    FileReader fileReader = new FileReader(jsonFile);
    Reader reader = new InputStreamReader(new FileInputStream(jsonFile), Charset.forName("utf-8"));
    int ch = 0;
    StringBuffer sb = new StringBuffer();
    while ((ch = reader.read()) != -1) {
      sb.append((char) ch);
    }
    fileReader.close();
    reader.close();
    jsonStr = sb.toString();
    return jsonStr;
  }

  public static String readResourcesJsonFile(String fileName) throws IOException {
    String jsonStr = "";
    ClassPathResource classPathResource = new ClassPathResource(fileName);
    Reader reader = new InputStreamReader(classPathResource.getInputStream(), Charset.forName("utf-8"));
    int ch = 0;
    StringBuffer sb = new StringBuffer();
    while ((ch = reader.read()) != -1) {
      sb.append((char) ch);
    }
    reader.close();
    jsonStr = sb.toString();
    return jsonStr;
  }

  /**
   * 写入2个文件,一个是日期在中间的backup文件,一个不带日期原始文件
   *
   * @param fileDir
   * @param fileBase
   * @param sets
   * @return
   * @throws IOException
   */
  public static boolean writeFileAndDateBackupFile(String fileDir, String fileBase, String sets) throws IOException {
    String dateStr = DateUtil.getNowToSecond(DateUtil.DATEFORMAT_SECOND);
    createDirAndBackup(fileDir);
    //如果超过备份数量,则清理最早一个备份文件
    List<String> backupFileNames = getFiles(getBackupPath(fileDir));
    if (backupFileNames.size() >= MAX_FILES_COUNT) {
      deleteFirstModifiedInDirectory(getBackupPath(fileDir));
    }
    //和最后修改的备份文件内容有差异时,再进行备份,否则不备份
    String lastBackup = getLastModifiedInDirectory(getBackupPath(fileDir));
    if (!lastBackup.trim().equals(sets.trim())) {
      writeFile(getBackupPath(fileDir) + PATH_SEPARATOR + fileBase + "_" + BACKUP_NAME + "_" + dateStr, sets);
    }
    writeFile(getFilePath(fileDir, fileBase), sets);
    return true;
  }

  public static String getBackupPath(String fileDir) {
    return fileDir + PATH_SEPARATOR + BACKUP_NAME;
  }

  public static String getFilePath(String fileDir, String fileName) {
    return fileDir + PATH_SEPARATOR + fileName;
  }

  /**
   * 把字符串写到文件
   *
   * @param filePath
   * @param sets
   * @return
   * @throws IOException
   */
  public static boolean writeFile(String filePath, String sets) throws IOException {
    FileWriter fw;
    fw = new FileWriter(filePath, Charset.forName("utf-8"));
    PrintWriter out = new PrintWriter(fw);
    out.write(sets);
    out.println();
    fw.close();
    out.close();
    return true;
  }

  /**
   * 创建目录和backup目录
   *
   * @param destDirName
   * @return
   */
  public static boolean createDirAndBackup(String destDirName) {
    createDir(destDirName);
    createDir(getBackupPath(destDirName));
    return true;
  }

  /**
   * 创建目录
   *
   * @param destDirName
   * @return
   */
  public static boolean createDir(String destDirName) {
    File dir = new File(destDirName);
    if (dir.exists()) {
      //System.out.println("创建目录" + destDirName + "失败,目标目录已经存在");
      return false;
    }
    //创建目录
    if (dir.mkdirs()) {
      //System.out.println("创建目录" + destDirName + "成功!");
      return true;
    } else {
      //System.out.println("创建目录" + destDirName + "失败!");
      return false;
    }
  }

  /**
   * 删除目录
   *
   * @return
   */
  public static boolean deleteDir(File dir) {
    if (!dir.exists()) {
      return false;
    }
    if (dir.isDirectory()) {
      // 递归删除目录中的子目录下
      for (String child : dir.list()) {
        deleteDir(new File(dir, child));
      }
    }
    dir.delete();
    return true;
  }

  public static boolean deleteDirPath(String path) {
    return deleteDir(new File(path));
  }

  /**
   * 获取目录下每个目录名称
   *
   * @param path
   * @return
   */
  public static List<String> getDirectories(String path) {
    List<String> directorys = new ArrayList<>();
    File file = new File(path);    //获取其file对象
    if (!file.exists()) {
      return directorys;
    }
    File[] fs = file.listFiles();  //遍历path下的文件和目录,放在File数组中
    for (File f : fs) {          //遍历File[]数组
      if (f.isDirectory())    //若非目录(即文件),则打印
      {
        directorys.add(f.getName());
      }
    }
    return directorys;
  }

  /**
   * 获取目录下所有文件
   *
   * @param path
   * @return
   */
  public static List<String> getFilesInDirectory(String path) {
    List<String> files = new ArrayList<>();
    File file = new File(path);    //获取其file对象
    if (!file.exists()) {
      return files;
    }
    File[] fs = file.listFiles();  //遍历path下的文件和目录,放在File数组中
    for (File f : fs) {          //遍历File[]数组
      if (f.isFile())    //若非目录(即文件),则打印
      {
        files.add(f.getName());
      }
    }
    return files;
  }

  /**
   * 获取目录最后修改的文件
   *
   * @param path
   * @return
   */
  public static String getLastModifiedInDirectory(String path) throws IOException {
    File lastFile = null;
    File file = new File(path);    //获取其file对象
    if (!file.exists()) {
      return "";
    }
    File[] fs = file.listFiles();  //遍历path下的文件和目录,放在File数组中
    long modified = 0;
    for (File f : fs) {          //遍历File[]数组
      if (f.isFile())    //若非目录(即文件),则打印
      {
        if (f.lastModified() > modified) {
          modified = f.lastModified();
          lastFile = f;
        }
      }
    }
    return readJsonFile(lastFile);
  }

  /**
   * 删除文件夹下,最早的一个文件
   *
   * @param path
   * @throws IOException
   */
  public static void deleteFirstModifiedInDirectory(String path) {
    File firstFile = null;
    File file = new File(path);    //获取其file对象
    if (!file.exists()) {
    }
    File[] fs = file.listFiles();  //遍历path下的文件和目录,放在File数组中
    long modified = 0;
    for (File f : fs) {          //遍历File[]数组
      if (f.isFile())    //若非目录(即文件),则打印
      {
        if (f.lastModified() < modified || modified == 0) {
          modified = f.lastModified();
          firstFile = f;
        }
      }
    }
    if (firstFile != null) {
      firstFile.delete();
    }
  }


  public static List<String> getResourcesDirectorys(String path) throws IOException {
    List<String> directorys = new ArrayList<>();
    Resource[] resources = new PathMatchingResourcePatternResolver().getResources(path + "/*");
    List<Resource> list = Arrays.asList(resources);
    list.forEach(r -> {
      directorys.add(r.getFilename());
    });
    return directorys;
  }

  /**
   * 获取目录下每个文件名称
   *
   * @param path
   * @return
   */
  public static List<String> getFiles(String path) {
    File file = new File(path);    //获取其file对象
    File[] fs = file.listFiles();  //遍历path下的文件和目录,放在File数组中
    List<String> files = new ArrayList<>();
    for (File f : fs) {          //遍历File[]数组
      if (!f.isDirectory())    //若非目录(即文件),则打印
      {
        files.add(f.getName());
      }
    }
    return files;
  }
}

 

posted @ 2020-10-30 10:49  然然1907  阅读(92)  评论(0编辑  收藏  举报