package org.jeecg.modules.dnc.utils.file;
|
|
import lombok.extern.slf4j.Slf4j;
|
import org.apache.commons.lang3.StringUtils;
|
import org.jeecg.common.api.vo.FileUploadResult;
|
import org.jeecg.common.util.SHA256Util;
|
import org.jeecg.modules.dnc.exception.ExceptionCast;
|
import org.jeecg.modules.dnc.utils.date.DateUtil;
|
import org.jeecg.modules.dnc.response.DocumentCode;
|
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.mock.web.MockMultipartFile;
|
import org.springframework.stereotype.Component;
|
import org.springframework.web.multipart.MultipartFile;
|
|
import javax.servlet.http.HttpServletResponse;
|
import java.io.*;
|
import java.math.BigDecimal;
|
import java.net.URLEncoder;
|
import java.nio.channels.FileChannel;
|
import java.nio.file.Files;
|
import java.nio.file.Path;
|
import java.nio.file.Paths;
|
import java.nio.file.StandardCopyOption;
|
import java.util.ArrayList;
|
import java.util.Date;
|
import java.util.List;
|
import java.util.zip.ZipEntry;
|
import java.util.zip.ZipOutputStream;
|
|
@Slf4j
|
@Component
|
public class FileUtilS {
|
|
private static String fileUploadFolder;
|
|
@Value("${fileHomePath}")
|
public void setFileUploadFolder(String fileUploadFolder) {
|
FileUtilS.fileUploadFolder = fileUploadFolder;
|
}
|
|
|
private static String fileNcFolder;
|
|
@Value("${fileNCPath}")
|
public void setFileNCFolder(String fileNcFolder) {
|
FileUtilS.fileNcFolder = fileNcFolder;
|
}
|
|
private static String addOrDelete;
|
|
@Value("${ncSend.addOrDelete}")
|
public void addOrDelete(String addOrDelete) {
|
FileUtilS.addOrDelete = addOrDelete;
|
}
|
|
|
/**
|
* 方法一:使用 FileWriter 写文件
|
* @param filepath 文件目录
|
* @param content 待写入内容
|
* @throws IOException
|
*/
|
public static void fileWriterSql(String filepath, String content) throws IOException {
|
OutputStreamWriter outputStreamWriter = null;
|
try {
|
File file = new File(filepath);
|
if (!file.exists()){
|
file.createNewFile();
|
}
|
FileOutputStream outputStream = new FileOutputStream(file);
|
if (outputStream != null){
|
outputStreamWriter = new OutputStreamWriter(outputStream, "utf-8");
|
outputStreamWriter.write(content);
|
outputStreamWriter.flush();
|
}
|
}
|
catch (IOException e) {
|
e.getMessage();
|
}
|
finally {
|
try {
|
if (outputStreamWriter != null){
|
outputStreamWriter.close();
|
}
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
}
|
|
public static boolean copyNcFile(String lastFile,String filePath) {
|
String absolutePathSend = lastFile;
|
FileChannel in = null;
|
FileChannel out = null;
|
try{
|
in = new FileInputStream(absolutePathSend).getChannel();
|
File file = new File(filePath);
|
if (!file.getParentFile().exists()){
|
//文件夹不存在 生成
|
file.getParentFile().mkdirs();
|
}
|
out = new FileOutputStream(filePath, true).getChannel();
|
out.transferFrom(in, 0, in.size());
|
try {
|
Thread.sleep(50);
|
} catch (InterruptedException e) {
|
e.printStackTrace();
|
}
|
in.close();
|
out.close();
|
|
}
|
catch (IOException e) {
|
e.printStackTrace();
|
try {
|
if (in != null) {
|
in.close();
|
}
|
if (out != null) {
|
out.close();
|
}
|
} catch (IOException e1) {
|
e1.printStackTrace();
|
}
|
return false;
|
}finally {
|
try {
|
if (in != null) {
|
in.close();
|
}
|
if (out != null) {
|
out.close();
|
}
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
return true;
|
}
|
|
/**
|
* 新建文件夹
|
* @param path
|
* @return
|
*/
|
|
public static boolean saveFileFromPath(String path) {
|
if (StringUtils.isEmpty(path)) {
|
return false;
|
}
|
String absolutePath = fileNcFolder + "/" + path ;
|
try {
|
boolean b = new File(absolutePath).mkdirs();
|
return b;
|
}catch (Exception e) {
|
return false;
|
}
|
}
|
|
/**
|
* 新建文件夹
|
* @param path
|
* @return
|
*/
|
|
public static boolean saveDeviceFromPath(String path) {
|
if (StringUtils.isEmpty(path)) {
|
return false;
|
}
|
String absolutePathSend = fileNcFolder + "/" + path + "/send" ;
|
String absolutePathRec = fileNcFolder + "/" + path + "/rec" ;
|
try {
|
boolean b = new File(absolutePathSend).mkdirs();
|
boolean c = new File(absolutePathRec).mkdirs();
|
return b;
|
}catch (Exception e) {
|
return false;
|
}
|
}
|
|
|
/**
|
* 修改文件夹
|
* @param path
|
* @return
|
*/
|
|
public static boolean updateFileFromPath(String path,String lastPathName) {
|
if (StringUtils.isEmpty(path)) {
|
return false;
|
}
|
String absolutePathLast = fileNcFolder + "/" + lastPathName ;
|
String absolutePathNew = fileNcFolder + "/" + path ;
|
try {
|
boolean b = new File(absolutePathLast).renameTo(new File(absolutePathNew));
|
return b;
|
}catch (Exception e) {
|
return false;
|
}
|
}
|
|
public static boolean uploadFileSend(MultipartFile file,String path) {
|
if(file == null || file.isEmpty()) {
|
return false;
|
}
|
//绝对路径
|
String absolutePath = fileNcFolder + "/" + path + "/send/";
|
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
|
// 目标文件路径+文件名
|
String targetFile = absolutePath + file.getOriginalFilename() ;
|
File toFile = new File(targetFile);
|
if (!toFile.getParentFile().exists()) {
|
toFile.mkdirs();
|
}
|
|
try {
|
file.transferTo(toFile);
|
} catch (Exception e) {
|
e.printStackTrace();
|
return false;
|
}
|
return true;
|
}
|
/**
|
* file转MultipartFile
|
*
|
* @param file file
|
* @return MultipartFile
|
*/
|
public static MultipartFile fileToMultipartFile(File file) {
|
MultipartFile result = null;
|
if (null != file) {
|
try (FileInputStream input = new FileInputStream(file)) {
|
result = new MockMultipartFile(file.getName().concat("temp"), file.getName(), "text/plain", input);
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
return result;
|
}
|
|
public static boolean copyFileRec(String lastFile) {
|
String absolutePathSend = lastFile;
|
//字符串替换
|
String absolutePathSendNotFile = lastFile.replace("\\rec\\","\\bak_rec\\");
|
String fileNameNoPath = (new File(lastFile)).getName();
|
String suffix = getFileSuffix(fileNameNoPath);
|
Integer recNum = absolutePathSendNotFile.lastIndexOf(fileNameNoPath);
|
if (suffix == null) {
|
|
absolutePathSendNotFile = absolutePathSendNotFile.substring(0,recNum) + fileNameNoPath+ "-" +
|
DateUtil.format(DateUtil.getNow(),DateUtil.STR_DATE_TIME_FULL);
|
/* absolutePathSendNotFile = absolutePathSendNotFile.replace(fileNameNoPath,
|
fileNameNoPath + "-" +DateUtil.format(DateUtil.getNow(),DateUtil.STR_DATE_TIME_FULL));*/
|
} else {
|
String name = fileNameNoPath.replace("." + suffix,"");
|
absolutePathSendNotFile = absolutePathSendNotFile.substring(0,recNum) + name+ "-" +
|
DateUtil.format(DateUtil.getNow(),DateUtil.STR_DATE_TIME_FULL) + "." + suffix;
|
}
|
try{
|
FileChannel in = new FileInputStream(absolutePathSend).getChannel();
|
File file = new File(absolutePathSendNotFile);
|
if (!file.getParentFile().exists()){
|
//文件夹不存在 生成
|
file.getParentFile().mkdirs();
|
}
|
FileChannel out = new FileOutputStream(absolutePathSendNotFile, true).getChannel();
|
out.transferFrom(in, 0, in.size());
|
in.close();
|
out.close();
|
return true;
|
}
|
catch (IOException e) {
|
e.printStackTrace();
|
return false;
|
}
|
}
|
|
public static boolean fileRecDelete(String lastFile) {
|
String absolutePathSend = lastFile;
|
Path path = Paths.get(lastFile);
|
try {
|
System.gc();
|
Files.delete(path);
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
try{
|
File file = new File(lastFile);
|
file.delete();
|
return true;
|
}
|
catch (Exception e) {
|
e.printStackTrace();
|
return false;
|
}
|
}
|
public static Boolean deleteFile(File file) {
|
//判断文件不为null或文件目录存在
|
if (file == null || !file.exists()) {
|
System.out.println("文件删除失败,请检查文件是否存在以及文件路径是否正确");
|
return false;
|
}
|
//获取目录下子文件
|
File[] files = file.listFiles();
|
//遍历该目录下的文件对象
|
for (File f : files) {
|
//判断子目录是否存在子目录,如果是文件则删除
|
if (f.isDirectory()) {
|
//递归删除目录下的文件
|
deleteFile(f);
|
} else {
|
//文件删除
|
f.delete();
|
//打印文件名
|
System.out.println("文件名:" + f.getName());
|
}
|
}
|
//文件夹删除
|
file.delete();
|
System.out.println("目录名:" + file.getName());
|
return true;
|
}
|
|
public static boolean copyFile(String lastFile ,String newFile, String fileName) {
|
String absolutePathSend = fileNcFolder + "/" + newFile + "/send/" + fileName;
|
String absolutePathSendNotFile = fileNcFolder + "/" + newFile + "/send/";
|
String absolutePath = fileUploadFolder + "/" + lastFile;
|
try{
|
File toFile = new File(absolutePathSendNotFile);
|
if("true".equals(addOrDelete)) {
|
deleteFile(toFile);
|
}
|
toFile.mkdirs();
|
FileChannel in = new FileInputStream(absolutePath).getChannel();
|
//查询文件是否存在
|
File file = new File(absolutePathSend);
|
//判断文件或文件夹是否存在
|
boolean flag = file.exists();
|
if(flag) {
|
//文件存在就要删除文件
|
System.gc();
|
file.delete();
|
}
|
String suffix = FileUtilS.getFileSuffix(fileName);
|
String newFileName = FileUtilS.getFilenameNonSuffix(fileName);
|
String zip = fileNcFolder + "/" + newFile + "/send/" + newFileName + "/";
|
|
FileChannel out = new FileOutputStream(absolutePathSend, true).getChannel();
|
out.transferFrom(in, 0, in.size());
|
if (suffix.equals("zip")) {
|
try {
|
FileZipUtil.unZipFiles(absolutePathSend,zip);
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
}
|
return true;
|
}
|
catch (IOException e) {
|
e.printStackTrace();
|
return false;
|
}
|
}
|
|
|
|
/**
|
* 删除文件
|
*
|
* @param filePath
|
* @return
|
*/
|
public static boolean deleteFile(String filePath) {
|
boolean flag = false;
|
File file = new File(filePath);
|
if (!file.exists()) {
|
return flag;
|
}
|
if (!file.isDirectory()) {
|
return flag;
|
}
|
String[] tempList = file.list();
|
File temp;
|
for (int i = 0; i < tempList.length; i++) {
|
if (filePath.endsWith(File.separator)) {
|
temp = new File(filePath + tempList[i]);
|
} else {
|
temp = new File(filePath + File.separator + tempList[i]);
|
}
|
if (temp.isFile()) {
|
temp.delete();
|
}
|
if (temp.isDirectory()) {
|
// 先删除文件夹里面的文件
|
deleteFile(filePath + "/" + tempList[i]);
|
// 再删除空文件夹
|
deleteFile(filePath + "/" + tempList[i]);
|
flag = true;
|
}
|
}
|
return flag;
|
}
|
|
|
/**
|
* 删除文件
|
*
|
* @param filePath
|
* @return
|
*/
|
public static boolean deleteNcFile(String filePath) {
|
boolean flag = false;
|
File file = new File(filePath);
|
if (!file.exists()) {
|
return flag;
|
}
|
boolean b = file.delete();
|
if (!b) {
|
System.out.println("文件删除失败: " + filePath);
|
}
|
return true;
|
}
|
|
/**
|
* 集成数据
|
* @param lastFile
|
* @param newFile
|
* @param zipString
|
* @return
|
*/
|
public static boolean copyFileNcIntegration(String lastFile ,String newFile,String zipString) {
|
String lastFileReName = fileNcFolder + "/" + lastFile ;
|
if (StringUtils.isNotBlank(zipString)) {
|
lastFileReName = lastFileReName + "." + zipString;
|
newFile = newFile + "." + zipString;
|
}
|
FileChannel in = null;
|
FileChannel out = null;
|
try{
|
in = new FileInputStream(lastFileReName).getChannel();
|
out = new FileOutputStream(newFile, true).getChannel();
|
out.transferFrom(in, 0, in.size());
|
in.close();
|
out.close();
|
return true;
|
}
|
catch (IOException e) {
|
e.printStackTrace();
|
return false;
|
} finally {
|
try {
|
in.close();
|
out.close();
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
|
}
|
}
|
|
|
|
|
/**
|
* 测试 更换名字
|
* @param lastFile
|
* @param newFile
|
* @param
|
* @return
|
*/
|
public static boolean copyFileUpName(String lastFile ,String newFile,String fixFileName,String ncFix) {
|
String lastFileReName = fileNcFolder + "/" + lastFile ;
|
if (StringUtils.isNotBlank(fixFileName)) {
|
lastFileReName = lastFileReName + "." + fixFileName;
|
newFile = newFile + "." + ncFix;
|
}
|
try {
|
long begintime = System.currentTimeMillis(); // 获取拷贝文件前的系统时间
|
|
Files.copy(Paths.get(lastFileReName),
|
Paths.get(newFile),
|
StandardCopyOption.REPLACE_EXISTING);
|
//方法二
|
/*// 创建一个带缓冲区的输入流
|
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(lastFileReName));
|
// 创建一个带缓冲区的输出流
|
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));
|
|
// 定义一个字节数组,作为缓冲区
|
byte[] buff = new byte[1024];
|
long begintime = System.currentTimeMillis(); // 获取拷贝文件前的系统时间
|
int len;
|
while ((len = bis.read(buff)) != -1) {
|
bos.write(buff, 0, len); // 从第一个字节开始,向文件写入len个字节
|
}
|
|
|
bis.close();
|
bos.close(); */
|
long endtime = System.currentTimeMillis(); // 获取文件拷贝结束时的系统时间
|
System.out.println("拷贝文件所消耗的时间是:" + (endtime - begintime) + "毫秒");
|
return true;
|
}
|
catch (Exception e) {
|
e.printStackTrace();
|
return false;
|
}
|
}
|
|
public static String fileSizeNC(String lastFile,String fileName){
|
String absolutePathSend = fileUploadFolder + "/" + lastFile + "/" + fileName;
|
File file = new File(absolutePathSend);
|
if (!file.exists()) {
|
return "0";
|
}
|
return String.valueOf(file.length());
|
}
|
|
/*产品树到设备树 NC*/
|
public static boolean copyFileNc(String lastFile ,String newFile, String fileName,String newFileName,String zipString) {
|
String absolutePathSend = fileUploadFolder + "/" + lastFile + "/" + fileName;
|
//判断文件夹是否存在
|
File file = new File(fileNcFolder + "/" + newFile + "/send/");
|
if (!file.exists()) {
|
file.mkdirs();
|
}
|
String abNewFileReName = fileNcFolder + "/" + newFile + "/send/" + newFileName ;
|
if (StringUtils.isNotBlank(zipString)) {
|
abNewFileReName = abNewFileReName + "." + zipString;
|
}
|
String zip = fileNcFolder + "/" + newFile + "/send/" + newFileName + "/";
|
try{
|
FileChannel in = new FileInputStream(absolutePathSend).getChannel();
|
FileChannel out = new FileOutputStream(abNewFileReName, true).getChannel();
|
out.transferFrom(in, 0, in.size());
|
if (zipString.equals("zip")) {
|
try {
|
FileZipUtil.unZipFiles(abNewFileReName,zip);
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
}
|
in.close();
|
out.close();
|
return true;
|
}
|
catch (IOException e) {
|
e.printStackTrace();
|
return false;
|
}
|
}
|
|
|
public static void compressFolder(File folder, String zipFilePath) throws IOException {
|
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFilePath));
|
compressFolder(folder, folder.getName(), zipOut);
|
zipOut.close();
|
}
|
|
private static void compressFolder(File folder, String parentFolder, ZipOutputStream zipOut) throws IOException {
|
if (folder.isFile()) {
|
String filePath = folder.getPath();
|
String entryPath = filePath.substring(parentFolder.length() + 1);
|
ZipEntry zipEntry = new ZipEntry(entryPath);
|
zipOut.putNextEntry(zipEntry);
|
FileInputStream fileIn = new FileInputStream(filePath);
|
byte[] buffer = new byte[1024];
|
int bytesRead;
|
while ((bytesRead = fileIn.read(buffer)) != -1) {
|
zipOut.write(buffer, 0, bytesRead);
|
}
|
fileIn.close();
|
zipOut.closeEntry();
|
} else {
|
for (File file : folder.listFiles()) {
|
compressFolder(file, parentFolder, zipOut);
|
}
|
}
|
}
|
/*产品树到设备树 NC*/
|
public static boolean copyFileNcToBak(String newFile, String newFileName,String fixFileName) {
|
String stringDate = DateUtil.format(DateUtil.getNow(),DateUtil.STR_DATE_STRING);
|
String absolutePathSend = null,abNewFileReName= null;
|
absolutePathSend = fileNcFolder + "/" + newFile + "/send/" + newFileName ;
|
abNewFileReName = fileNcFolder + "/" + newFile + "/send_bak/" + "/" +stringDate+ "/" + newFileName + "_" + DateUtil.format(DateUtil.getNow(),DateUtil.STR_DATE_TIME_FULL) ;
|
if (StringUtils.isNotBlank(fixFileName) ) {
|
if(!fixFileName.equals("zip")) {
|
absolutePathSend = absolutePathSend + "." + fixFileName ;
|
abNewFileReName = abNewFileReName + "." + fixFileName ;
|
} else {
|
copyFileBakZip(new File(absolutePathSend),new File(abNewFileReName));
|
return true;
|
}
|
}
|
File targetFile = new File(abNewFileReName);
|
if(!targetFile.getParentFile().exists()){
|
targetFile.getParentFile().mkdirs();
|
}
|
try{
|
FileChannel in = new FileInputStream(absolutePathSend).getChannel();
|
FileChannel out = new FileOutputStream(abNewFileReName, true).getChannel();
|
out.transferFrom(in, 0, in.size());
|
in.close();
|
out.close();
|
return true;
|
}
|
catch (IOException e) {
|
e.printStackTrace();
|
return false;
|
}
|
|
}
|
|
public static Boolean deletePathNameFile(File file) {
|
//判断文件不为null或文件目录存在
|
if (file == null || !file.exists()) {
|
System.out.println("文件删除失败,请检查文件是否存在以及文件路径是否正确");
|
return false;
|
}
|
//获取目录下子文件
|
File[] files = file.listFiles();
|
//遍历该目录下的文件对象
|
for (File f : files) {
|
//判断子目录是否存在子目录,如果是文件则删除
|
if (f.isDirectory()) {
|
//递归删除目录下的文件
|
deletePathNameFile(f);
|
} else {
|
//文件删除
|
f.delete();
|
//打印文件名
|
System.out.println("文件名:" + f.getName());
|
}
|
}
|
//文件夹删除
|
file.delete();
|
return true;
|
}
|
|
|
public static Boolean deleteZipFromToSend(String newFile,String newFileName,String zipString) {
|
String abNewFileReName = fileNcFolder + "/" + newFile + "/send/" + newFileName ;
|
if (StringUtils.isNotBlank(zipString)) {
|
if (zipString.equals("zip")) {
|
abNewFileReName = abNewFileReName + "." + zipString;
|
return fileRecDelete(abNewFileReName);
|
}
|
}
|
return true;
|
}
|
|
public static Boolean deleteFilePathZip(String newFile,String newFileName,String zipString) {
|
String abNewFileReName = fileNcFolder + "/" + newFile + "/send/" + newFileName ;
|
//分类
|
if (StringUtils.isNotBlank(zipString)) {
|
//有问题
|
if (zipString.equals("zip")) {
|
String stringDate = DateUtil.format(DateUtil.getNow(),DateUtil.STR_DATE_STRING);
|
String abNewFileReNameBak = fileNcFolder + "/" + newFile + "/send_bak/" + "/" +stringDate+ "/" + newFileName + "_" +
|
DateUtil.format(DateUtil.getNow(),DateUtil.STR_DATE_TIME_FULL) ;
|
copyFileBakZip(new File(abNewFileReName),new File(abNewFileReNameBak));
|
return deleteFile(new File(abNewFileReName));
|
}
|
abNewFileReName = abNewFileReName + "." + zipString;
|
}
|
copyFileNcToBak(newFile,newFileName,zipString);
|
return fileRecDelete(abNewFileReName);
|
}
|
|
public static void copyFileBakZip(File file, File target) {
|
target = new File(target, file.getName());
|
if (!target.exists()) {
|
target.mkdirs();
|
}
|
if (file.isDirectory()) {
|
File[] files = file.listFiles();
|
for (File f : files) {
|
if (f.isDirectory()) {
|
copyFileBakZip(f, target);
|
}
|
else {
|
copyFileDeleteZip(f, target);
|
}
|
}
|
} else {
|
copyFileDeleteZip(file, target);
|
}
|
}
|
|
public static void copyFileDeleteZip(File file, File directory) {
|
try {
|
FileInputStream input = new FileInputStream(file);
|
FileOutputStream output = new FileOutputStream(new File(directory, file.getName()));
|
byte[] buff = new byte[8192];
|
int len = -1;
|
while ((len = input.read(buff)) > -1) {
|
output.write(buff);
|
}
|
input.close();
|
output.close();
|
} catch (Exception e) {
|
|
}
|
}
|
|
|
//改名
|
public static FileUploadResult uploadFileUpdateFileName(MultipartFile file,String fileName ,String suffix) {
|
if(file == null || file.isEmpty())
|
return null;
|
Date currentDate = DateUtil.getNow();
|
String monthStr = DateUtil.format(currentDate, DateUtil.STR_YEAR_MONTH);
|
//相对路径
|
String relativePath = "/" + monthStr + "/" + DateUtil.getDayStr(currentDate) + "/";
|
//绝对路径
|
String absolutePath = fileUploadFolder + "/" + monthStr + "/" + DateUtil.getDayStr(currentDate) + "/";
|
String fileNameNonSuffix = getFilenameNonSuffix(fileName);
|
if(fileNameNonSuffix == null)
|
return null;
|
String encodeFileName = SHA256Util.getSHA256Str(fileNameNonSuffix + System.currentTimeMillis());
|
Long fileSize = file.getSize();
|
boolean b = uploadFile(file, absolutePath, encodeFileName);
|
if(!b)
|
return null;
|
FileUploadResult dto = new FileUploadResult();
|
dto.setFileName(fileNameNonSuffix);
|
dto.setFileEncodeName(encodeFileName);
|
dto.setFilePath(relativePath);
|
dto.setFileSize(fileSize);
|
dto.setFileSuffix(suffix);
|
return dto;
|
}
|
|
public static boolean deleteFileNewRec(String filePath) {
|
boolean flag = false;
|
File file = new File(filePath);
|
if (!file.exists()) {
|
return flag;
|
}
|
boolean b = file.delete();
|
if (!b) {
|
try {
|
System.gc();
|
Path path = Paths.get(filePath);
|
Files.deleteIfExists(path);
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
return true;
|
}
|
|
|
public static FileUploadResult uploadFile(MultipartFile file) {
|
if(file == null || file.isEmpty())
|
return null;
|
String fileName = file.getOriginalFilename();
|
String suffix = getFileSuffix(fileName);
|
// if(StringUtils.isBlank(suffix))
|
// return null;
|
Date currentDate = DateUtil.getNow();
|
String monthStr = DateUtil.format(currentDate, DateUtil.STR_YEAR_MONTH);
|
//相对路径
|
String relativePath = "/" + monthStr + "/" + DateUtil.getDayStr(currentDate) + "/";
|
//绝对路径
|
String absolutePath = fileUploadFolder + "/" + monthStr + "/" + DateUtil.getDayStr(currentDate) + "/";
|
String fileNameNonSuffix = getFilenameNonSuffix(fileName);
|
if(fileNameNonSuffix == null)
|
return null;
|
String encodeFileName = SHA256Util.getSHA256Str(fileNameNonSuffix + System.currentTimeMillis());
|
Long fileSize = file.getSize();
|
boolean b = uploadFile(file, absolutePath, encodeFileName);
|
if(!b)
|
return null;
|
FileUploadResult dto = new FileUploadResult();
|
dto.setFileName(fileNameNonSuffix);
|
dto.setFileEncodeName(encodeFileName);
|
dto.setFilePath(relativePath);
|
dto.setFileSize(fileSize);
|
dto.setFileSuffix(suffix);
|
return dto;
|
}
|
|
public static void downLoadFile(HttpServletResponse response, String fileName, String filePath, String toFileName) {
|
String absolutePath = fileUploadFolder + filePath;
|
File file = new File(absolutePath , fileName);
|
if(file.exists()) {
|
byte[] buffer = new byte[1024];
|
FileInputStream fis = null;
|
BufferedInputStream bis = null;
|
try {
|
response.setHeader("Content-Type", "application/octet-stream;charset=utf-8"); // 告诉浏览器输出内容为流
|
//response.setHeader("Content-Disposition", "attachment;fileName="+ new String(toFileName.getBytes("UTF-8"),"ISO-8859-1"));
|
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(toFileName, "UTF-8"));
|
fis = new FileInputStream(file);
|
bis = new BufferedInputStream(fis);
|
OutputStream os = response.getOutputStream();
|
int i = bis.read(buffer);
|
while (i != -1) {
|
os.write(buffer, 0, i);
|
i = bis.read(buffer);
|
}
|
}catch (Exception e) {
|
log.error(e.getMessage(), e.getStackTrace());
|
}finally {
|
if(bis != null) {
|
try {
|
bis.close();
|
} catch (IOException e) {
|
}
|
}
|
if(fis != null) {
|
try {
|
fis.close();
|
} catch (IOException e) {
|
}
|
}
|
}
|
}else {
|
ExceptionCast.cast(DocumentCode.DOC_PUBLISH_FILE_NOT_EXIST);
|
}
|
}
|
/**
|
* 上传文件工具类
|
* @param multipartFile
|
* @param path
|
* @param fileNewName 新的文件名
|
* @return
|
*/
|
public static boolean uploadFile(MultipartFile multipartFile, String path, String fileNewName) {
|
File targetFile = new File(path, fileNewName);
|
if(!targetFile.getParentFile().exists()){
|
targetFile.getParentFile().mkdirs();
|
}
|
try {
|
multipartFile.transferTo(targetFile);
|
return true;
|
} catch (Exception e) {
|
log.error(e.getMessage(), e.getStackTrace());
|
return false;
|
}
|
}
|
|
/**
|
/**
|
* 获取文件后缀 无后缀文件返回NULL
|
* @param fileName
|
* @return
|
*/
|
public static String getFileSuffix(String fileName) {
|
if (fileName.contains(".")) {
|
String suffix = fileName.substring(fileName.lastIndexOf('.') + 1);
|
return suffix;
|
}else {
|
return null;
|
}
|
|
}
|
|
/**
|
* 获取文件名 不带后缀和点号
|
* @param fileName
|
* @return
|
*/
|
public static String getFilenameNonSuffix(String fileName) {
|
if (fileName.contains(".")) {
|
String filename = fileName.substring(0, fileName.lastIndexOf('.'));
|
return filename;
|
}else {
|
return fileName;
|
}
|
|
}
|
|
public static List<String> readFile(String fileEncodeName, String filePath) {
|
String absolutePath = fileUploadFolder + filePath;
|
File file = new File(absolutePath , fileEncodeName);
|
if(!file.exists() || file.isDirectory())
|
ExceptionCast.cast(DocumentCode.DOC_PUBLISH_FILE_NOT_EXIST);
|
String charset = checkFileEncode(file);
|
if(charset == null)
|
ExceptionCast.cast(DocumentCode.DOC_PUBLISH_FILE_NOT_EXIST);
|
List<String> readList = new ArrayList<>();
|
String tempString = null;
|
BufferedReader reader = null;
|
try {
|
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
|
while ((tempString = reader.readLine()) != null) {
|
readList.add(tempString);
|
}
|
if(readList.isEmpty())
|
return null;
|
return readList;
|
} catch (Exception e) {
|
log.error(e.getMessage(), e.getStackTrace());
|
return null;
|
} finally {
|
if(reader != null) {
|
try {
|
reader.close();
|
} catch (IOException e) {
|
log.error(e.getMessage(), e.getStackTrace());
|
}
|
}
|
}
|
}
|
|
private static String checkFileEncode(File file) {
|
String charset = "GBK";
|
byte[] first3Bytes = new byte[3];
|
BufferedInputStream bis = null;
|
try {
|
boolean checked = false;
|
bis = new BufferedInputStream(new FileInputStream(file));
|
bis.mark(0);
|
int read = bis.read(first3Bytes, 0, 3);
|
if (read == -1)
|
return charset;
|
if(first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE ) {
|
charset = "UTF-16LE";
|
checked = true;
|
}else if ( first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF ) {
|
charset = "UTF-16BE";
|
checked = true;
|
}else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB && first3Bytes[2] == (byte) 0xBF ) {
|
charset = "UTF-8";
|
checked = true;
|
}
|
bis.reset();
|
if (!checked) {
|
while ((read = bis.read()) != -1 ) {
|
if ( read >= 0xF0 )
|
break;
|
if ( 0x80 <= read && read <= 0xBF ) // 单独出现BF以下的,也算是GBK
|
break;
|
if ( 0xC0 <= read && read <= 0xDF ) {
|
read = bis.read();
|
if ( 0x80 <= read && read <= 0xBF ) // 双字节 (0xC0 - 0xDF) (0x80 - 0xBF),也可能在GBK编码内
|
continue;
|
else
|
break;
|
} else if ( 0xE0 <= read && read <= 0xEF ) {
|
// 也有可能出错,但是几率较小
|
read = bis.read();
|
if ( 0x80 <= read && read <= 0xBF ) {
|
read = bis.read();
|
if ( 0x80 <= read && read <= 0xBF ) {
|
charset = "UTF-8";
|
break;
|
} else
|
break;
|
} else {
|
break;
|
}
|
}
|
}
|
}
|
return charset;
|
}catch (Exception e) {
|
return null;
|
}finally {
|
if(bis != null) {
|
try {
|
bis.close();
|
} catch (IOException e) {
|
}
|
}
|
}
|
|
}
|
|
public static String changeFileFormat(String flow) {
|
BigDecimal flows = new BigDecimal(flow);
|
if (flows.compareTo(new BigDecimal(0)) > 0 && flows.compareTo(new BigDecimal(1024)) < 0) {//小于1M
|
return flows.toString() + "B";
|
} else if(flows.compareTo(new BigDecimal(1024)) >= 0 && flows.compareTo(new BigDecimal(1048576)) < 0){
|
BigDecimal result = flows.divide(new BigDecimal(1024),2,BigDecimal.ROUND_HALF_UP);
|
return result.toString() + "KB";
|
} else if(flows.compareTo(new BigDecimal(1048576)) >= 0 && flows.compareTo(new BigDecimal(1073741824)) < 0){
|
BigDecimal result = flows.divide(new BigDecimal(1048576),2,BigDecimal.ROUND_HALF_UP);
|
return result.toString() + "MB";
|
} else if(flows.compareTo(new BigDecimal(1073741824)) >= 0 && flows.compareTo(new BigDecimal("1099511627776")) < 0){
|
BigDecimal result = flows.divide(new BigDecimal(1073741824),2,BigDecimal.ROUND_HALF_UP);
|
return result.toString() + "GB";
|
} else if(flows.compareTo(new BigDecimal("1099511627776")) >= 0 && flows.compareTo(new BigDecimal("1125899906842624")) < 0){
|
BigDecimal result = flows.divide(new BigDecimal("1099511627776"),2,BigDecimal.ROUND_HALF_UP);
|
return result.toString() + "TB";
|
} else if(flows.compareTo(new BigDecimal("1125899906842624")) >= 0){
|
BigDecimal result = flows.divide(new BigDecimal("1125899906842624"),2,BigDecimal.ROUND_HALF_UP);
|
return result.toString() + "PB";
|
}else {
|
return "0";
|
}
|
}
|
|
|
public static String changeFileFormatKb(String flow) {
|
BigDecimal flows = new BigDecimal(flow);
|
if (flows.compareTo(new BigDecimal(0)) > 0 && flows.compareTo(new BigDecimal(1024)) < 0) {//小于1M
|
return flows.toString() + "B";
|
} else if(flows.compareTo(new BigDecimal(1024)) >= 0){
|
BigDecimal result = flows.divide(new BigDecimal(1024),2,BigDecimal.ROUND_HALF_UP);
|
return result.toString() + "KB";
|
} else {
|
return "0";
|
}
|
}
|
|
|
}
|