一、写字符到txt文件

字符流,只能操作文本文件,不能操作图片,视频等非文本文件。当我们单纯读或者写文本文件时 使用字符流 其他情况使用字节流。

有两种方法:一是使用字符输出流,二时使用字节输出流

1、保存内容到txt文件

1)、使用字符输出流

public void addLog(SystemLogDto systemLog) {
        try {
            long id = SnowflakeManager.nextValue();
            systemLog.setId(id);
            systemLog.setHasFile(0);
            int maxLength = 4000;
            String inParamPrefixStr = "请求参数:\r\n";
            String outParamPrefixStr = "返回数据:\r\n";
            String inParam = systemLog.getInParam();
            String outParam = systemLog.getOutParam();
            if (inParam.length() > maxLength || outParam.length() > maxLength) {
                String data ="";
                String suffixPath = File.separator + DateUtil.toStringNoInterval(systemLog.getCreateTime(), 8);
                FileUtil.createDir(filePathPrefix + suffixPath);
                String category = getCategory(systemLog.getCategory());
                String title = null == systemLog.getTitle() ? "" : systemLog.getTitle();
                String date = DateUtil.toStringNoInterval(systemLog.getCreateTime(), 17);
                String fileName = date + "_" + category + "_" + title + "_" + systemLog.getId().toString()+".txt"; // 文件名
                File file = new File(filePathPrefix + suffixPath + File.separator + fileName);
                if (!file.exists()) file.createNewFile();
                systemLog.setHasFile(1);
                systemLog.setFilePath(suffixPath + File.separator + fileName);
                FileWriter fileWriter = new FileWriter(file, true); // 创建FileWriter对象
                    data = inParamPrefixStr + inParam+"\r\n"+outParamPrefixStr + outParam; // 内容
                    fileWriter.write(data); // 写到缓冲区
                    systemLog.setInParam(getText(inParam));
                    systemLog.setOutParam(getText(outParam));
                fileWriter.flush(); // 写到文件
                fileWriter.close(); // 释放资源
            }
            SystemLog systemLog1 = dozerMapper.map(systemLog, SystemLog.class);
            systemLogDao.insertSelective(systemLog1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

注意:拼接成完整的文件地址要使用File.separator,同样,截取文件名和文件的目录也要使用File.separator,

String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
String path = filePath.substring(0, filePath.lastIndexOf(File.separator));

而不能使用\,如下所示:

String fileName = filePath.substring(filePath.lastIndexOf("\\") + 1);
String path = filePath.substring(0, filePath.lastIndexOf("\\"));

2)、使用字节输出流

功能说明:将接口的请求头保存到本地电脑。

serviceImpl

@Service("outstoreUploadLogService")
@Transactional
@Slf4j
public class OutstoreUploadLogServiceImpl implements OutstoreUploadLogService {
    @Resource
    private OutstoreUploadLogMapper outstoreUploadLogMapper;
    @Value("${system.file.tempPath}")
    private String tempPath;

    @Override
    public Result saveToTxt(JSONObject jsonObject) {
        // 将jsonObject转为字节数组输入流
        byte[] bytes = jsonObject.toString().getBytes();
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        String suffix = ".txt";
        String path = FileUtil.saveFile(inputStream, tempPath, suffix);
        return Result.operating("请求体保存成功", true, ResultCode.SUCCESS,path);
    }
}

配置文件如下:

system.file.tempPath=d:/upload/cmdptcp/fileUpload

2、将字符写到txt文件并下载

功能说明:将数据库的公钥下载下来。

controller

/**
     * 公钥下载
     * @param id
     * @param response
     * @return
     */
    @PostMapping("/uploadPublikey")
    @Log("公钥下载")
    public void uploadPublikey (Long id,HttpServletResponse response)throws Exception {
        equipmentService.uploadPublikey(id,response);
    }

service

@Override
    public void uploadPublikey(Long id, HttpServletResponse response) throws Exception {
        Equipment equipment = equipmentDao.selectByPrimaryKey(id);
        String enterpriseName = enterpriseDao.getName(equipment.getEntityId());
        String fileName = enterpriseName + "_" + equipment.getEquipmentNo() + ".txt"; // 文件名
        String content = equipment.getProdPubKey(); // 内容
        FileUtil.downloadFile2(fileName, content, response);
    }

downloadFile2方法

public static void downloadFile2(String fileName, String content, HttpServletResponse response) throws IOException {
        response = setResponse(fileName, response);
        OutputStream outputStream = response.getOutputStream(); // 不用创建直接获取字节输出流
        BufferedOutputStream buffer = new BufferedOutputStream(outputStream); // 使用缓冲流,即给字节输出流加一个缓冲区
        buffer.write(content.getBytes()); // 写到字节缓冲区
        buffer.flush(); // 写到文件
        buffer.close(); // 释放资源
        outputStream.close();
    }

二、获取指定位置的txt文件的内容

代码如下:

public class TxtAnalysisTest {
    public static void main(String[] args) throws IOException {
        String lineTxt_cr = null;//行读字符串
        String encoding="GBK";
        File file = new File("C:\\Users\\miracle\\Desktop\\a.txt");
        if(file.isFile() && file.exists()) { //判断文件是否存在
            InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);//考虑到编码格式
            BufferedReader bufferedReader = new BufferedReader(read); // 字符缓冲输入流
            StringBuffer xpStr = new StringBuffer(); //文件文本字符串
            while((lineTxt_cr = bufferedReader.readLine()) != null){
            //处理字符串lineTxt_cr
                xpStr.append(lineTxt_cr);
            }
            // 释放资源
            bufferedReader.close();
        read.close();
            System.out.println(xpStr);
        }
    }
}

三、读取指定位置的文件并下载

功能说明:将本地电脑的文件下载下来。

代码如下:

@Override
    public void download(Long id, HttpServletResponse response) throws IOException {
        OutstoreUploadLog outstoreUploadLog = outstoreUploadLogMapper.selectByPrimaryKey(id);
        String filePath = outstoreUploadLog.getFilePath();
String fileName
= filePath.substring(filePath.lastIndexOf("\\") + 1); // 得到文件名 String path = filePath.substring(0,filePath.lastIndexOf("\\") ); // 得到目录 FileUtil.downloadFile(path, fileName, response); }

注意:downloadFile第一个参数为path,第二个参数为文件名。

工具类

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Slf4j
public class FileUtil {

    //压缩目录
    public static void CompressDir(String filePath) {
        try {
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(filePath + ".zip"));
            Zip(filePath, filePath.lastIndexOf(File.separator), out);
            out.closeEntry();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void Zip(String path, int baseindex, ZipOutputStream out) throws Exception {
        // 要压缩的目录或文件
        File file = new File(path);
        File[] files;
        if (file.isDirectory()) {// 若是目录,则列出所有的子目录和文件
            files = file.listFiles();
        } else {// 若为文件,则files数组只含有一个文件
            files = new File[1];
            files[0] = file;
        }
        for (File f : files) {
            if (f.isDirectory()) {
                // 去掉压缩根目录以上的路径串,一面ZIP文件中含有压缩根目录父目录的层次结构
                String pathname = f.getPath().substring(baseindex + 1);
                // 空目录也要新建哟个项
                out.putNextEntry(new ZipEntry(pathname + "/"));
                // 递归
                Zip(f.getPath(), baseindex, out);
            } else {
                // 去掉压缩根目录以上的路径串,一面ZIP文件中含有压缩根目录父目录的层次结构
                String pathname = f.getPath().substring(baseindex + 1);
                if (f.length() > 100 * 1024 * 1024) {
                    throw new Exception("文件大小不能大于100M");
                }
                // 新建项为一个文件
                out.putNextEntry(new ZipEntry(pathname));
                // 读文件
                BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
                int c;
                while ((c = in.read()) != -1)
                    out.write(c);
                in.close();
            }
        }
    }

    /**
     * 删除文件夹
     *
     * @param sPath
     * @return boolean
     */
    public static boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            File parent = file.getParentFile();
            if (parent.isDirectory() && parent.listFiles().length <= 0) {
                parent.delete();
                File temp = parent.getParentFile();
                deleteFile(temp.getAbsolutePath());
            }
            flag = true;
        } else {
            File parent = new File(sPath);
            if (parent.isDirectory() && parent.listFiles().length <= 0) {
                parent.delete();
                File temp = parent.getParentFile();
                deleteFile(temp.getAbsolutePath());
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 删除目录及目录下的所有文件不删除顶级目录
     *
     * @param sPath
     * @return boolean
     */
    public static boolean deleteDirFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            File parent = file.getParentFile();
            if (parent.isDirectory() && parent.listFiles().length <= 0) {
                parent.delete();
                File temp = parent.getParentFile();
                deleteFile(temp.getAbsolutePath());
            }
            flag = true;
        } else {
            File parent = new File(sPath);
            if (parent.isDirectory()) {
                if (parent.listFiles().length <= 0) {
                    parent.delete();
                } else {
                    File[] files = parent.listFiles();
                    for (File f : files) {
                        deleteDirFile(f.getAbsolutePath());
                    }
                }
                flag = true;
            }
        }
        return flag;
    }



    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file, String tempPath) throws Exception {
        File toFile = null;
        if (!file.equals("") && file.getSize() > 0) {
            InputStream ins = file.getInputStream();
            File tempFile = new File(tempPath);
            if (!(tempFile.exists() && tempFile.isDirectory())) {
                tempFile.mkdirs();
            }
            toFile = new File(tempFile + File.separator + file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除转换存储的临时文件
    public static void deleteMultipartFile(MultipartFile file, String tempPath) {
        File tempFile = new File(tempPath + File.separator + file.getOriginalFilename());
        tempFile.delete();
    }

    //生成目录
    public static File createDir(String path) {
        File file = new File(path);
        if (!(file.exists() && file.isDirectory())) {
            file.mkdirs();
        }
        return file;
    }

    public static Map<String, String> upload(MultipartFile file, String basePath) {
        Map<String, String> map = new HashMap<>();
        String dateStr = DateUtil.toStringNoInterval(new Date(), 8);
        if (basePath.contains("\\")) {
            basePath = basePath.replace("\\", File.separator);
        }
        File f = createDir(basePath + File.separator + dateStr);
        //获取文件的原始名
        String oldName = file.getOriginalFilename();
        //获取文件的后缀名
        String suffix = oldName.substring(oldName.lastIndexOf("."));
        //使用uuid设置新的文件名,防止文件名重复
        String newName = UUID.randomUUID() + suffix;
        //文件保存
        try {
            file.transferTo(new File(f, newName));
            map.put("fileName", newName);
            map.put("uploadPath", dateStr);
        } catch (IOException e) {
            log.error("文件上传发生异常:", e);
            e.printStackTrace();
        }
        return map;
    }


    /**
     * 流转字节数组
     *
     * @param in
     * @return
     * @throws IOException
     */
    public static byte[] streamToByteArray(InputStream in) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n;
        while (-1 != (n = in.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }

    /**
     * 读取资源目录下的文件内容
     *
     * @param filePath
     * @param clazz
     * @return
     * @throws IOException
     */
    public static List<String> readResourceFile(String filePath, Class<?> clazz) throws IOException {
        InputStream in = getResourceStream(filePath, clazz);
        InputStreamReader reader = new InputStreamReader(in);
        BufferedReader buffReader = new BufferedReader(reader);
        String strTmp;
        List<String> content = new ArrayList<>();
        while ((strTmp = buffReader.readLine()) != null) {
            content.add(strTmp);
        }
        buffReader.close();
        return content;
    }

    public static InputStream getResourceStream(String filePath, Class<?> clazz) {
        return clazz.getClassLoader().getResourceAsStream(filePath);
    }

    /**
     * 将资源目录下的文件生成到磁盘
     *
     * @param sourcePath
     * @param targetPath
     * @param clazz
     */
    public static void createToFileByResource(String sourcePath, String targetPath, Class<?> clazz) {
        File file = new File(targetPath);
        if (!file.exists()) {
            InputStream is = clazz.getClassLoader().getResourceAsStream(sourcePath);
            OutputStream os = null;
            try {
                os = new FileOutputStream(targetPath);
                int len;
                byte[] bytes = new byte[1024];
                while ((len = is.read(bytes)) != -1) {//边读边写
                    os.write(bytes, 0, len);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {//关闭资源,防止内存泄漏
                    os.close();
                    is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public static BufferedOutputStream createFile(String filePath, String fileName) throws IOException {
        File file = createDir(filePath);
        file = new File(filePath + File.separator + fileName);
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(file.getPath()));
        return stream;
    }

    /**
     * 将文件字节转为 b/kb/mb/g的大小形式
     *
     * @param fileSize
     * @return
     */
    public static String transByte(String fileSize) {
        // 格式化,保留两位小数
        DecimalFormat df = new DecimalFormat("#.00");
        Double d = Double.parseDouble(fileSize);
        d = d / 1024;
        if (d < 1024) {
            return df.format(d) + "KB";
        }
        d = d / 1024;
        if (d < 1024) {
            return df.format(d) + "MB";
        }
        d = d / 1024;

        return df.format(d) + "G";

    }

    public static List<String> readTxtByLine(File file, String tempPath) {
        List<String> list = new ArrayList<>();
        try {
            list = readTxtByLine(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public static List<String> readTxtByLine(File file) {
        List<String> list = new ArrayList<>();
        InputStreamReader reader = null;
        BufferedReader bufferedReader = null;
        try {
            //判断文件是否存在
            if (file.isFile() && file.exists()) {
                reader = new InputStreamReader(new FileInputStream(file), "UTF-8");
                bufferedReader = new BufferedReader(reader);
                String lineTxt;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    list.add(lineTxt);
                }
            }
            file.delete();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("按行读取txt文件异常:{}", e);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    public static String saveFile(InputStream in, String basePath, String suffix) {
        String path = null;
        BufferedOutputStream os = null;
        try {
            String dateStr = DateUtil.toStringNoInterval(new Date(), 8);
            if (basePath.contains("\\")) {
                basePath = basePath.replace("\\", File.separator);
            }
            File f = createDir(basePath + File.separator + dateStr);
            f = new File(f, UUID.randomUUID() + suffix);
            os = new BufferedOutputStream(new FileOutputStream(f));
            int len;
            byte[] bytes = new byte[1024 * 1024];
            while ((len = in.read(bytes)) != -1) {//边读边写
                os.write(bytes, 0, len);
            }
            path = f.getPath();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭资源,防止内存泄漏
            try {
                if (os != null) os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return path;
    }

    /**
     * base64转文件保存
     *
     * @param base64
     * @param basePath
     * @param suffix   文件后缀
     * @param fileName 文件名
     * @return
     */
    public static String[] base64ToFile(String base64, String basePath, String suffix, String fileName) {
        String dateStr = DateUtil.toStringNoInterval(new Date(), 8);
        if (basePath.contains("\\")) {
            basePath = basePath.replace("\\", File.separator);
        }
        File f = createDir(basePath + File.separator + dateStr);
        if (null == fileName) {
            //补齐后缀
            suffix = suffix.trim();
            if (!suffix.startsWith(".") && suffix.indexOf(".") == -1) {
                suffix = "." + suffix;
            }
            fileName = UUID.randomUUID() + suffix;
        }
        try {
            byte[] buffer = new BASE64Decoder().decodeBuffer(base64);
            File file = new File(f, fileName);
            FileOutputStream out = new FileOutputStream(file);
            out.write(buffer);
            out.close();
            String[] path = {dateStr, fileName};
            return path;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 文件转base64
     *
     * @param filePath
     * @return
     */
    public static String fileToBase64(String filePath) {
        if (filePath == null) {
            return null;
        }
        try {
            byte[] b = Files.readAllBytes(Paths.get(filePath));
            return Base64.getEncoder().encodeToString(b);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过流下载文件
     *
     * @param fileName 文件名
     * @param response
     * @throws IOException
     */
    public static void downloadFile(String filePath, String fileName, HttpServletResponse response) throws IOException {
        File file = new File(filePath + File.separator + fileName);
        InputStream in = new FileInputStream(file);
        response = setResponse(fileName, response);
        int len = 0;
        byte bytes[] = new byte[1024];
        OutputStream out = response.getOutputStream();
        while ((len = in.read(bytes)) > 0) {
            out.write(bytes, 0, len);
        }
        in.close();
        out.close();
    }
    /**
     * 通过流下载文件
     *
     * @param fileNewName 文件名
     * @param response
     * @throws IOException
     */
    public static void downloadFile1(String filePath, String fileNewName, HttpServletResponse response) throws IOException {
        File file = new File(filePath);
        InputStream in = new FileInputStream(file);
        response = setResponse(fileNewName, response);
        int len = 0;
        byte bytes[] = new byte[1024];
        OutputStream out = response.getOutputStream();
        while ((len = in.read(bytes)) > 0) {
            out.write(bytes, 0, len);
        }
        in.close();
        out.close();
    }
    /**
     * 设置响应信息
     *
     * @param fileName
     * @param response
     * @throws UnsupportedEncodingException
     */
    private static HttpServletResponse setResponse(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
        response.setHeader("Access-Control-Expose-Headers", "content-disposition");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        return response;
    }
}

 

 

posted on 2022-08-19 17:43  周文豪  阅读(151)  评论(0编辑  收藏  举报