文件工具类

1. 读取文件比如本地的json数据,本地文本等

2. 写入文件

3. 复制文件

4. 移动文件

5. 删除文件

import com.alibaba.fastjson.util.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

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

/**
 *  文件工具类
 */
public class FileUtil {

    private static Logger logger = Logger.getLogger(FileUtil.class);
    // 文件扩展分隔符
    private final static String FILE_EXTENSION_SEPARATOR = ".";

    /**
     * 读取文件
     * @param filePath      文件路径
     * @param charsetName   编码名称
     * @return
     */
    public static String readFile(String filePath, String charsetName) {
        File file = new File(filePath);
        StringBuilder fileContent = new StringBuilder();
        if (file == null || !file.isFile()) {
            return null;
        }
        BufferedReader reader = null;
        try {
            InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName);
            reader = new BufferedReader(is);
            String line = null;
            while ((line = reader.readLine()) != null) {
                if (!fileContent.toString().equals("")) {
                    fileContent.append("\r\n");
                }
                fileContent.append(line);
            }
            return fileContent.toString();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        } finally {
            IOUtils.close(reader);
        }
    }

    /**
     * 读取文件转化为字符串列表
     * @param filePath      文件路径
     * @param charsetName   编码名称
     * @return
     */
    public static List<String> readFileToList(String filePath, String charsetName) {
        File file = new File(filePath);
        List<String> fileContent = new ArrayList<String>();
        if (file == null || !file.isFile()) {
            return null;
        }

        BufferedReader reader = null;
        try {
            InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName);
            reader = new BufferedReader(is);
            String line = null;
            while ((line = reader.readLine()) != null) {
                fileContent.add(line);
            }
            return fileContent;
        } catch (IOException e) {
            logger.error(e.getMessage());
            return null;
        } finally {
            IOUtils.close(reader);
        }
    }

    /**
     * 将内容写入文件
     * @param filePath  文件路径
     * @param content   写入的内容
     * @param append    如果为ture,则是写入文件的末尾,如果为false,则是先清空文件,在将内容写入文件中
     * @return
     */
    public static boolean writeFile(String filePath, String content, boolean append){
        if (StringUtils.isEmpty(content)) {
            return false;
        }

        FileWriter fileWriter = null;
        try {
            makeDirs(filePath);
            fileWriter = new FileWriter(filePath, append);
            fileWriter.write(content);
            return true;
        } catch (IOException e) {
            logger.error(e.getMessage());
            return false;
        } finally {
            IOUtils.close(fileWriter);
        }
    }

    /**
     * 将字符串列表写入文件
     * @param filePath      文件路径
     * @param contentList   字符串列表
     * @param append        如果为ture,则是写入文件的末尾,如果为false,则是先清空文件,在将内容写入文件中
     * @return
     */
    public static boolean writeFile(String filePath, List<String> contentList, boolean append) {
        if (contentList == null || contentList.size() == 0) {
            return false;
        }

        FileWriter fileWriter = null;
        try {
            makeDirs(filePath);
            fileWriter = new FileWriter(filePath, append);
            int i = 0;
            for (String line : contentList) {
                if (i++ > 0) {
                    fileWriter.write("\r\n");
                }
                fileWriter.write(line);
            }
            return true;
        } catch (IOException e) {
            logger.error(e.getMessage());
            return false;
        } finally {
            IOUtils.close(fileWriter);
        }
    }

    /**
     * 将InputStream写入文件中,首先清除文件中的内容,在进行写入
     * @param file
     * @param stream
     * @return
     */
    public static boolean writeFile(File file, InputStream stream){
        return writeFile(file, stream, false);
    }

    /**
     * 将内容写入文件,首先清除文件中的内容,在进行写入
     * @param filePath
     * @param content
     * @return
     */
    public static boolean writeFile(String filePath, String content){
        return writeFile(filePath, content, false);
    }

    /**
     * 将字符串列表写入文件,首先清除文件中的内容,在进行写入
     * @param filePath
     * @param contentList
     * @return
     */
    public static boolean writeFile(String filePath, List<String> contentList){
        return writeFile(filePath, contentList, false);
    }

    /**
     * 将InputStream写入文件中,首先清除文件中的内容,在进行写入
     * @param filePath
     * @param stream
     * @return
     */
    public static boolean writeFile(String filePath, InputStream stream){
        return writeFile(filePath != null ? new File(filePath) : null, stream, false);
    }

    /**
     * 将InputStream写入文件中
     * @param file      文件
     * @param stream    流
     * @param append    如果为ture,则是写入文件的末尾,如果为false,则是先清空文件,在将内容写入文件中
     * @return
     */
    public static boolean writeFile(File file, InputStream stream, boolean append){
        OutputStream o = null;
        try {
            makeDirs(file.getAbsolutePath());
            o = new FileOutputStream(file, append);
            byte data[] = new byte[1024];
            int length = -1;
            while ((length = stream.read(data)) != -1) {
                o.write(data, 0, length);
            }
            o.flush();
            return true;
        } catch (FileNotFoundException e) {
            throw new RuntimeException("FileNotFoundException occurred. ", e);
        } catch (IOException e) {
            logger.error(e.getMessage());
            return false;
        } finally {
            IOUtils.close(o);
            IOUtils.close(stream);
        }
    }

    /**
     * 复制文件
     * @param sourceFilePath    源文件路径
     * @param destFilePath      目的文件路径
     * @return
     */
    public static boolean copyFile(String sourceFilePath, String destFilePath){
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(sourceFilePath);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            return false;
        }
        return writeFile(destFilePath, inputStream);
    }

    /**
     * 删除文件
     * @param path
     * @return
     */
    public static boolean deleteFile(String path){
        if (StringUtils.isEmpty(path)) {
            return true;
        }

        File file = new File(path);
        if (!file.exists()) {
            return true;
        }
        if (file.isFile()) {
            return file.delete();
        }
        if (!file.isDirectory()) {
            return false;
        }
        for (File f : file.listFiles()) {
            if (f.isFile()) {
                f.delete();
            } else if (f.isDirectory()) {
                deleteFile(f.getAbsolutePath());
            }
        }
        return file.delete();
    }

    /**
     * 移动文件
     * @param srcFile
     * @param destFile
     */
    public static void moveFile(File srcFile, File destFile){
        boolean rename = srcFile.renameTo(destFile);
        if (!rename) {
            copyFile(srcFile.getAbsolutePath(), destFile.getAbsolutePath());
            deleteFile(srcFile.getAbsolutePath());
        }
    }

    public static void moveFile(String sourceFilePath, String destFilePath){
        if (StringUtils.isEmpty(sourceFilePath) || StringUtils.isEmpty(destFilePath)) {
            logger.error("Both sourceFilePath and destFilePath cannot be null");
        }
        moveFile(new File(sourceFilePath), new File(destFilePath));
    }

    /**
     * 获取文件名称,包括后缀
     * <pre>
     *     getFileName(null)               =   null
     *     getFileName("")                 =   ""
     *     getFileName("   ")              =   "   "
     *     getFileName("a.mp3")            =   "a.mp3"
     *     getFileName("a.b.rmvb")         =   "a.b.rmvb"
     *     getFileName("abc")              =   "abc"
     *     getFileName("c:\\")              =   ""
     *     getFileName("c:\\a")             =   "a"
     *     getFileName("c:\\a.b")           =   "a.b"
     *     getFileName("c:a.txt\\a")        =   "a"
     *     getFileName("/home/admin")      =   "admin"
     *     getFileName("/home/admin/a.txt/b.mp3")  =   "b.mp3"
     * </pre>
     * @param filePath  文件路径
     * @return
     */
    public static String getFileName(String filePath){
        if (StringUtils.isEmpty(filePath)) {
            return filePath;
        }
        int filePosi = filePath.lastIndexOf(File.separator);
        return (filePosi == -1) ? filePath : filePath.substring(filePosi + 1);
    }

    /**
     * 获取文件名称,不带有后缀
     * <pre>
     *     getFileNameWithoutExtension(null)               =   null
     *     getFileNameWithoutExtension("abc")              =   "abc"
     *     getFileNameWithoutExtension("a.mp3")            =   "a"
     *     getFileNameWithoutExtension("a.b.rmvb")         =   "a.b"
     *     getFileNameWithoutExtension("c:\\a.b")           =   "a"
     *     getFileNameWithoutExtension("/home/admin")      =   "admin"
     *     getFileNameWithoutExtension("/home/admin/a.txt/b.mp3")  =   "b"
     * </pre>
     * @param filePath  文件路径
     * @return
     */
    public static String getFileNameWithoutExtension(String filePath){
        if (StringUtils.isEmpty(filePath)) {
            return filePath;
        }

        int extenPosi = filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR);
        int filePosi = filePath.lastIndexOf(File.separator);
        if (filePosi == -1) {
            return (extenPosi == -1) ? filePath : filePath.substring(0, extenPosi);
        }
        if (extenPosi == -1) {
            return filePath.substring(filePosi + 1);
        }
        return (filePosi < extenPosi) ? filePath.substring(filePosi + 1, extenPosi) : filePath.substring(filePosi + 1);
    }

    /**
     * 获取文件的目录名称
     * @param filePath
     * @return
     */
    public static String getFolderName(String filePath){
        if (StringUtils.isEmpty(filePath)) {
            return filePath;
        }

        int filePosi = filePath.lastIndexOf(File.separator);
        return (filePosi == -1) ? "" : filePath.substring(0, filePosi);
    }

    public static boolean makeDirs(String filePath){
        String folderName = getFolderName(filePath);
        if (StringUtils.isEmpty(folderName)) {
            return false;
        }

        File folder = new File(folderName);
        return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.hexiang.utils; import java.io.*; /** * FileUtil. Simple file operation class. * * @author BeanSoft * */ public class FileUtil { /** * The buffer. */ protected static byte buf[] = new byte[1024]; /** * Read content from local file. FIXME How to judge UTF-8 and GBK, the * correct code should be: FileReader fr = new FileReader(new * InputStreamReader(fileName, "ENCODING")); Might let the user select the * encoding would be a better idea. While reading UTF-8 files, the content * is bad when saved out. * * @param fileName - * local file name to read * @return * @throws Exception */ public static String readFileAsString(String fileName) throws Exception { String content = new String(readFileBinary(fileName)); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(String fileName, String encoding) throws Exception { String content = new String(readFileBinary(fileName), encoding); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(InputStream in) throws Exception { String content = new String(readFileBinary(in)); return content; } /** * Read content from local file to binary byte array. * * @param fileName - * local file name to read * @return * @throws Exception */ public static byte[] readFileBinary(String fileName) throws Exception { FileInputStream fin = new FileInputStream(fileName); return readFileBinary(fin); } /** * 从输入流读取数据为二进制字节数组. * @param streamIn * @return * @throws IOException */ public static byte[] readFileBinary(InputStream streamIn) throws IOException { BufferedInputStream in = new BufferedInputStream(streamIn); ByteArrayOutputStream out = new ByteArrayOutputStream(10240); int len; while ((len

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值