File

作者: 青丝如梦 | 来源:发表于2020-05-19 17:52 被阅读0次
  • 获取文件分隔符:
File.separator
  • 创建文件路径:
file.getParentFile().mkdirs();
  • 将一个文件移动到另一个目录下:
    /**
     * 移动文件
     *
     * @param oldFile old file
     * @param newFile new file
     */
    public static void removeFile(File oldFile, File newFile) {
        newFile.getParentFile().mkdirs();
        if (oldFile.renameTo(newFile)) {
            log.info("文件移动到{}成功!", newFile.getAbsolutePath());
        } else {
            log.error("文件移动到{}失败。", newFile.getAbsolutePath());
        }
    }
  • 删除文件:
//        删除文件
        if (file.delete()) {
            log.info("删除文件:{}成功!", pathname);
        } else {
            log.error("删除文件:{}失败...", pathname);
        }
  • 判断文件是否存在, 不存在则创建路径与文件:
package com.util;

import lombok.extern.slf4j.Slf4j;

import java.io.File;

/**
 * @author 
 * 日期 2019/11/5 12:06
 * 描述 TODO
 * @version 1.0
 * @since 1.0
 */
@Slf4j
public class FileUtil {

    /**
     * 判断文件是否存在, 不存在则创建路径与文件
     *
     * @param filePath 路径
     * @return 创建成功的文件
     * @throws Exception
     */
    public static File checkExist(String filePath) throws Exception {
        File file = new File(filePath);
        if (file.isFile()) {
            log.info(filePath + " 文件存在!");
        } else {
            log.info("文件不存在,开始创建 ......");
            File parentPath = new File(file.getParent());
            boolean mkdirs = parentPath.mkdirs();
            if (mkdirs) {
                log.info("创建文件夹成功!");
                boolean newFile = file.createNewFile();
                if (newFile) {
                    log.info("创建文件成功!");
                } else {
                    log.error("创建文件失败。");
                }
            }else{
                log.error("创建文件夹失败,文件夹可能已存在,继续创建文件。");
                boolean newFile = file.createNewFile();
                if (newFile) {
                    log.info("创建文件成功!");
                } else {
                    log.error("创建文件失败。");
                }
            }
        }
        return file;
    }
}

相关文章

网友评论

      本文标题:File

      本文链接:https://www.haomeiwen.com/subject/zuqpohtx.html