一些常用操作文件的方法

如果你不相信努力和时光,那么成果就会是第一个选择辜负你的。不要去否定你自己的过去,也不要用你的过去牵扯你现在的努力和对未来的展望。不是因为拥有希望你才去努力,而是去努力了,你才有可能看到希望的光芒。一些常用操作文件的方法,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

package com.baidu.kmai.process.utils;

import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.io.FileNotFoundException;
import java.io.BufferedInputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Component
@Slf4j
public class FileUtils {


    /**
     * 获取txt文件内容并按行放入list中
     */
    public static List<String> getFileContext(String path) throws Exception {
        InputStreamReader fileReader = new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List<String> list = new ArrayList<String>();
        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            if (str.trim().length() > 2) {
                list.add(str);
            }
        }
        return list;
    }

    /**
     * 向某个文件中输出文本
     *
     * @param list
     * @param filePath
     */
    public static void setFileWriter(List<String> list, String filePath) {
//        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream()));
        // 确保文件夹存在
        int index = filePath.lastIndexOf("/");
        String substring = filePath.substring(0, index);
        isPathExist(substring);
        // 先将文件的内容写空
        writeEmpty(filePath);
        BufferedWriter bufferedWriter = null;
        try {
            // true表示不覆盖原来的内容,而是加到文件的后面。若要覆盖原来的内容,直接省略这个参数就好
//            bufferedWriter = new BufferedWriter(new FileWriter(filePath, true));
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, true),
                    StandardCharsets.UTF_8));

            for (int i = 0; i < list.size(); i++) {
                bufferedWriter.write(list.get(i));
                bufferedWriter.newLine();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.flush();
                    bufferedWriter.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }


    /**
     * 读取某路径下的文件并下载
     *
     * @param response response
     * @param filepath 文件路径
     * @return 返回结果 成功或者文件不存在
     */
    public static String getContextAndDownloadFile(HttpServletResponse response, String filepath) {
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        String[] split = filepath.split("/");
        String fileName = split[split.length - 1];
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    java.net.URLEncoder.encode(fileName, "UTF-8"));
        } catch (UnsupportedEncodingException e2) {
            e2.printStackTrace();
        }
        BufferedReader br = null;
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            br = new BufferedReader(new InputStreamReader(new FileInputStream(filepath), Charset.defaultCharset()));
            String line = null;
            while ((line = br.readLine()) != null) {
                os.write(line.getBytes(StandardCharsets.UTF_8));
                os.write("\r\n".getBytes(StandardCharsets.UTF_8));
                os.flush();
            }

        } catch (FileNotFoundException e1) {
            return "系统找不到指定的文件";
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "success";
    }

    /**
     * 直接下载文件
     *
     * @param response
     * @param fileName
     * @param list
     * @return
     */
    public static String downloadFile(HttpServletResponse response, String fileName, List<String> list) {
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    java.net.URLEncoder.encode(fileName, "UTF-8"));
        } catch (UnsupportedEncodingException e2) {
            e2.printStackTrace();
        }
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            for (int i = 0; i < list.size(); i++) {
                String line = list.get(i);
                os.write(line.getBytes(StandardCharsets.UTF_8));
                os.write("\r\n".getBytes(StandardCharsets.UTF_8));
                os.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";

    }

    /**
     * @param response
     * @param filepath
     * @return
     */
    public static String downloadFileZip(HttpServletResponse response, String filepath) {
        response.setContentType("application/octet-stream");
        String[] split = filepath.split("/");
        String fileName = split[split.length - 1];
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    java.net.URLEncoder.encode(fileName, "UTF-8"));
        } catch (UnsupportedEncodingException e2) {
            e2.printStackTrace();
        }

        BufferedInputStream bufferedInputStream = null;
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            bufferedInputStream = new BufferedInputStream(new FileInputStream(new File(filepath)));
            byte[] bytes = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = bufferedInputStream.read(bytes)) != -1) {
                os.write(bytes);
                os.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufferedInputStream != null) {
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "success";
    }


    /**
     * 将指定的文件夹压缩成zip
     * zipFold("D:/test.zip", "D:/test")
     *
     * @param zipFileName   压缩的路径及文件名
     * @param inputFilePath 要压缩的文件路径
     * @throws Exception
     */
    public static void zipFold(String zipFileName, String inputFilePath) throws Exception {
        zip(zipFileName, new File(inputFilePath));
    }


    private static void zipFold(ZipOutputStream out, File f, String base) throws Exception {
        if (f.isDirectory()) {
            File[] fl = f.listFiles();
            base = base.length() == 0 ? "" : base + "/";
            for (int i = 0; i < fl.length; i++) {
                zipFold(out, fl[i], base + fl[i].getName());
            }
        } else {
            out.putNextEntry(new ZipEntry(base));
            FileInputStream in = new FileInputStream(f);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(in);
            byte[] bytes = new byte[1024 * 1024];
            int i;
            while ((i = bufferedInputStream.read(bytes)) != -1) {
                out.write(bytes, 0, bytes.length);
                out.flush();
            }
            out.flush();
            in.close();
        }

    }


    private static void zip(String zipFileName, File inputFile) throws Exception {
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
        zipFold(out, inputFile, "");
        out.close();
    }


    /**
     * 将某个文件中的内容写空
     *
     * @param filepath
     */
    public static void writeEmpty(String filepath) {
        File file = new File(filepath);
        if (file.exists()) {
            file.delete();
        }
    }

    /**
     * 判断文件夹是否存在,如果不存在则创建
     *
     * @param dirPath 文件夹磁盘路径
     */
    public static void isPathExist(String dirPath) {
        File file = new File(dirPath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }


    public static String getPinyin(String china) {
        HanyuPinyinOutputFormat formart = new HanyuPinyinOutputFormat();
        formart.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        formart.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        formart.setVCharType(HanyuPinyinVCharType.WITH_V);
        char[] arrays = china.trim().toCharArray();
        String result = "";
        try {
            for (int i = 0; i < arrays.length; i++) {
                char ti = arrays[i];
                if (Character.toString(ti).matches("[\\u4e00-\\u9fa5]")) { // 匹配是否是中文
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(ti, formart);
                    result += temp[0];
                } else {
                    result += ti;
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }
        String replace = result.replace("(", "(").replace(")", ")");
        return replace;
    }

}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/192068.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!