文件IO流,读取与下载

本文深入探讨了Java中文件IO流的使用,重点讲解如何高效地读取文件内容以及实现文件的下载操作。通过实例代码,详细阐述了不同类型的流及其在文件操作中的应用。
摘要由CSDN通过智能技术生成

文件IO流,读取与下载

package com.liu.demo.controller;

import com.liu.demo.service.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;

/**
 * @author Administrator
 */
@Slf4j(topic="ArticleController")
@RestController
@ResponseBody
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @GetMapping("/exportResult")
    public void exportLog(HttpServletResponse response) throws IOException {
    	//字符串的拼接是数据库查询的结果
        //插入时间
        Date date = new Date();
        DateFormat df = DateFormat.getDateTimeInstance();
        String articleData=df.format(date);
        articleData+=articleService.getAllArticle().toString();
        articleData+="\r\n";
        exportTxt(response,articleData);
    }


    public void exportTxt(HttpServletResponse response,String text) throws IOException {
        response.setCharacterEncoding("utf-8");
        //设置响应的内容类型
        response.setContentType("text/plain");
        //设置文件的名称和格式,设置名称格式,没有这个中文名称无法显示
        response.addHeader("Content-Disposition","attachment;filename="+ genAttachmentFileName( "查询结果", "JSON_FOR_UCC_")  + ".txt");
        BufferedOutputStream buff = null;
        ServletOutputStream outStr = null;

        outStr = response.getOutputStream();
        buff = new BufferedOutputStream(outStr);
        buff.write(text.getBytes("UTF-8"));

        buff.flush();
        buff.close();
        outStr.close();

    }


    /**
     * 防止中文文件名显示出错
     * @param cnName
     * @param defaultName
     * @return
     */
    public  String genAttachmentFileName(String cnName, String defaultName) {
        try {
            cnName = new String(cnName.getBytes("gb2312"), "ISO8859-1");
        } catch (Exception e) {
            cnName = defaultName;
        }
        return cnName;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值