java fileutils 字符集_FileUtils.java

FileUtils.java

package com.june.util;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.URLEncoder;

import java.time.LocalDate;

import java.time.format.DateTimeFormatter;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import org.springframework.web.multipart.MultipartFile;

public class FileUtils {

private FileUtils() {}

/**

* 下载文件

* @param response

* @param fileDirPath 文件保存目录路径

* @param fileName 文件名

*/

public static void download(HttpServletResponse response, String fileDirPath, String fileName)

throws Exception {

response.reset();

response.setHeader("Content-Disposition", "attachment; filename=\""

+ URLEncoder.encode(fileName, "UTF-8") + "\"");

response.setContentType("application/octet-stream; charset=UTF-8");

File file = new File(getRealPath(fileDirPath), fileName);

InputStream is = new FileInputStream(file);

OutputStream os = response.getOutputStream();

byte[] data = IOUtils.toByteArray(is);

IOUtils.closeQuietly(is);

response.setHeader("Content-Length", "" + data.length);

IOUtils.write(data, os);

IOUtils.closeQuietly(os);

}

/**

* 上传文件

* @param file 文件

* @param dirPath 文件所在目录路径

*/

public static void upload(MultipartFile file, String dirPath)

throws Exception {

String fileName = file.getOriginalFilename();

String realDirPath = getRealPath(dirPath) + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));

File dir = new File(realDirPath);

//判断上传目录是否存在,若不存在则创建

if (!dir.exists()) {

dir.mkdir();

}

StringBuilder filePath = new StringBuilder();

filePath.append(realDirPath)

.append(File.separator)

.append(System.currentTimeMillis())

.append(fileName.substring(fileName.indexOf('.')));

InputStream is = file.getInputStream();

OutputStream os = new FileOutputStream(filePath.toString());

IOUtils.copy(is, os);

IOUtils.closeQuietly(is);

IOUtils.closeQuietly(os);

}

/**

* 根据文件classpath路径获取真实路径

* @param path classpath下的路径

* @return 真实路径

*/

public static String getRealPath(String path) {

return FileUtils.class.getResource(path).getPath();

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值