JAVA在页面查看或下载服务器上的日志

时间:2024-03-11 14:52:58

1.配置

FileUtils类所需jar包的maven地址

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.2</version>
</dependency>

2.代码

参数为日志文件的相对路径

package com.example.demo.io;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author Sue
 * @create 2019-05-08 10:03
 **/
@Controller
public class LogUtil {
    /**
     * 读取txt文件的内容
     *
     * @param file 想要读取的文件对象
     * @return 返回文件内容
     */
    public static String txt2String(File file) {
        StringBuilder result = new StringBuilder();
        try {
            //构造一个BufferedReader类来读取文件
            BufferedReader br = new BufferedReader(new FileReader(file));
            String s = null;
            //使用readLine方法,一次读一行
            while ((s = br.readLine()) != null) {
                result.append(System.lineSeparator() + s);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    @GetMapping("/getLog")
    public void main(HttpServletRequest request, HttpServletResponse response,String theFileName) {
        String property = System.getProperty("user.dir");
        String absolutePath = property + File.separator + theFileName;
        File file = new File(absolutePath);

//        File file = new File("D:\\logback.2019-04-29.log");
        System.out.println(txt2String(file) + ">");
        try {
            response.getWriter().write(txt2String(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/download")
    public ResponseEntity<byte[]> downLoad(HttpServletRequest request,String theFileName) throws Exception, FileNotFoundException {
        HttpHeaders headers = new HttpHeaders();
        String property = System.getProperty("user.dir");
        String absolutePath = property + File.separator + theFileName;
        File file = new File(absolutePath);
//        File file = new File("D:\\logback.2019-04-29.log");
        String fileName = file.getName();
        if (file.exists()) {
            //下载显示的文件名,解决中文名称乱码问题
            String userAgent = request.getHeader("user-agent").toLowerCase();
            String downloadFielName;

            if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
                downloadFielName = URLEncoder.encode((fileName), "UTF-8");
            } else {
                downloadFielName = new String((fileName).getBytes("UTF-8"), "iso-8859-1");
            }
            headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + downloadFielName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        } else {
            throw new FileNotFoundException("文件不存在");
        }
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);


    }
}