JAVA导入txt文件并按行读取内容封装成实体以及导出下载

业务背景:
前台页面支持用户上传txt类型的文件,用做一些服务的配置,我们需求将改文件解析,读取里面的内容,并封装成接口参数,再调第三方接口;

上代码:

   @PostMapping("/uploadHost")
    @RequiresRoles("admin")
    public Result<Boolean> uploadHost(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        if (multipartFile.isEmpty()) {
            throw new FuxiException("文件不能为空");
        }
        //转成file类型
        File file = FileUtils.multipartFileToFile(multipartFile);
        assert file != null;
        InputStreamReader read = null;
        List<TxtEntity>entityList = null;
        try {
           //先读入再放入缓冲流里面按行读取
            read = new InputStreamReader(new FileInputStream(file), "GBK");
            entityList = new ArrayList<>();
            BufferedReader br = new BufferedReader(read);
            String lineTxt;

            while ((lineTxt = br.readLine()) != null) {
            //跳过注释和空行
                if (lineTxt.startsWith("#") || StringUtils.isEmpty(lineTxt)){
                    continue;
                }
                //我这个地方是按空格分割,可以根据自己的业务场景编写规则
                String[] strings = lineTxt.split(" ");
                //封装成实体
                TxtEntity txtEntity = new TxtEntity();
                txtEntity.setIp(strings[0]);
                txtEntity.setHostName(strings[1]);
                if (strings.length > 2){
                    txtEntity.setServer(strings[2]);
                }
                entityList.add(txtEntity);
            }
            if (entityList.isEmpty()){
                return Result.error(500,"文件不能为空");
            }
             //调第三方接口,这里可以写自己的代码逻辑
            Integer result = fuxiInterfaceRestService.hostsImport(entityList);
            if (result == 0) {
                fileManageService.updateFileInfo(BehaviorEnum.HOST);
                return Result.success();
            }
            return Result.error(500,"上传失败");
        } catch (IOException e) {
            log.info(String.format("host文件解析失败 : %s",e.getMessage()));
            throw new IOException("文件解析错误");
        }finally {
            if (read != null){
                read.close();
            }
        }

    }
   /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if ("".equals(file) || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(Objects.requireNonNull(file.getOriginalFilename()));
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

下载文件:
我直接贴个工具类,可以下载成xml、properties、text文件

package com.ddb.common.utils;

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

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @Author zqf
 * @Date 2022/7/29 10:11
 * @Description: 文件工具
 */
@Slf4j
public class FileUtils {

    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if ("".equals(file) || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(Objects.requireNonNull(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();
        }
    }


    /**
     * 导出xml 需要HttpServletResponse response
     */
    public static void creatAndSendXML(HttpServletResponse response, String fileName, String xml){
        BufferedOutputStream output = null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/x-msdownload");
            response.addHeader("Content-Disposition","attachment;filename="+fileName);
            output = new BufferedOutputStream(response.getOutputStream());
            output.write(xml.getBytes());
            output.flush();   //不可少
            response.flushBuffer();//不可少
        }catch (Exception e){
            e.printStackTrace();
            log.error("导出文件文件出错:{}",e);
        }finally {
            try {
                assert output != null;
                output.close();
            }catch (Exception e){
                log.error("关闭流对象出错 e:{}",e);
                e.printStackTrace();
            }
        }
    }
    /**
     * 导出xml 需要HttpServletResponse response
     */
    public static void creatAndSendYml(HttpServletResponse response, String fileName, String yml){
        BufferedOutputStream output = null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/x-msdownload");
            response.addHeader("Content-Disposition","attachment;filename="+fileName);
            output = new BufferedOutputStream(response.getOutputStream());
            output.write(yml.getBytes());
            output.flush();   //不可少
            response.flushBuffer();//不可少
        }catch (Exception e){
            e.printStackTrace();
            log.error("导出文件文件出错:{}",e);
        }finally {
            try {
                assert output != null;
                output.close();
            }catch (Exception e){
                log.error("关闭流对象出错 e:{}",e);
                e.printStackTrace();
            }
        }
    }


    /**
     * 导出Properties 需要HttpServletResponse response
     */
    public static void exportProperties(HttpServletResponse response, String fileName, String yml){
        BufferedOutputStream output = null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/x-msdownload");
            response.addHeader("Content-Disposition","attachment;filename="+fileName);
            output = new BufferedOutputStream(response.getOutputStream());
            output.write(yml.getBytes());
            output.flush();   //不可少
            response.flushBuffer();//不可少
        }catch (Exception e){
            e.printStackTrace();
            log.error("导出文件文件出错:{}",e);
        }finally {
            try {
                assert output != null;
                output.close();
            }catch (Exception e){
                log.error("关闭流对象出错 e:{}",e);
                e.printStackTrace();
            }
        }
    }
    /**
     * 导出普通文本
     * @param response
     * @param text
     */
    public static void exportTxt(HttpServletResponse response,String text){
        response.setCharacterEncoding("utf-8");
        //设置响应的内容类型
        response.setContentType("text/plain");
        //设置文件的名称和格式  设置名称格式,没有这个中文名称无法显示
        response.addHeader("Content-Disposition","attachment;filename="
                + genAttachmentFileName( "host", "JSON_FOR_UCC_")
                + ".txt");
        BufferedOutputStream buff = null;
        ServletOutputStream outStr = null;
        try {
            outStr = response.getOutputStream();
            buff = new BufferedOutputStream(outStr);
            buff.write(text.getBytes(StandardCharsets.UTF_8));
            buff.flush();
            buff.close();
        } catch (Exception e) {
            log.error("导出文件文件出错:{}",e);
        } finally {try {
            assert buff != null;
            buff.close();
            outStr.close();
        } catch (Exception e) {
            log.error("关闭流对象出错 e:{}",e);
        }
        }
    }


    public static String genAttachmentFileName(String cnName, String defaultName) {
        try {
            cnName = new String(cnName.getBytes("gb2312"), "ISO8859-1");
        } catch (Exception e) {
            cnName = defaultName;
        }
        return cnName;
    }
}

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值