package com.jiayou.peis.report.biz.utils;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Base64;
public class FileUtil {
/**
* 根据URL下载文件(pdf/图片)并转换为Base64
* @param fileUrl
* @return
*/
public static String transUrlToBase64(String fileUrl){
try {
URL url = new URL(fileUrl);
InputStream inputStream = url.openStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
IOUtils.copy(inputStream,outputStream);
byte[] byteArray = outputStream.toByteArray();
return Base64.getEncoder().encodeToString(byteArray);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 下载文件
*
* @param filePath 文件路径
* @param response 响应体
*/
@SneakyThrows
public static void downloadFile(String filePath, HttpServletResponse response) {
File file = new File(filePath);
//输入流,读取文件内容
FileInputStream fileInputStream = new FileInputStream(file.getPath());
//输出流,将文件写回浏览器
ServletOutputStream servletOutputStream = response.getOutputStream();
//响应格式(图片)
response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes()));
response.addHeader("Content-Length", String.valueOf(file.length()));
response.setContentType("application/octet-stream");
int len = 0;
byte[] bytes = new byte[1024];
while ((len = fileInputStream.read(bytes)) != -1) {
servletOutputStream.write(bytes, 0, len);
servletOutputStream.flush();
}
fileInputStream.close();
servletOutputStream.close();
}
/**
* 下载远程文件并保存到本地
*
* @param remoteFilePath-远程文件路径
* @param localFilePath-本地文件路径(带文件名)
*/
public static void downloadFile1(String remoteFilePath, String localFilePath) {
URL urlfile = null;
HttpURLConnection httpUrl = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
File f = new File(localFilePath);
try {
urlfile = new URL(remoteFilePath);
httpUrl = (HttpURLConnection) urlfile.openConnection();
httpUrl.connect();
bis = new BufferedInputStream(httpUrl.getInputStream());
bos = new BufferedOutputStream(new FileOutputStream(f));
int len = 2048;
byte[] b = new byte[len];
while ((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
}
bos.flush();
bis.close();
httpUrl.disconnect();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bis.close();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 下载远程文件并保存到本地
*
* @param remoteFilePath-远程文件路径
* @param localFilePath-本地文件路径(带文件名)
*/
public static void downloadFile2(String remoteFilePath, String localFilePath) {
URL website = null;
ReadableByteChannel rbc = null;
FileOutputStream fos = null;
try {
website = new URL(remoteFilePath);
rbc = Channels.newChannel(website.openStream());
fos = new FileOutputStream(localFilePath);//本地要存储的文件地址 例如:test.txt
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(rbc!=null){
try {
rbc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void test() throws FileNotFoundException {
String path="http://10.32.1.123/report/download/userReport/2/2023/07/14/729600323349381120/604527●伍仁华●职业健康体检报告.pdf";
String pdfName = path.substring(path.lastIndexOf("/")+1);
String tempDir = "C:\\Users\\Administrator\\Desktop\\新建文件夹\\path\\zip\\";//System.getProperty("java.io.tmpdir") + "temp" + File.separator;
File tempDirFile = new File(tempDir);
if (!tempDirFile.exists()) tempDirFile.mkdirs();
// 压缩包名称
String zipName = "压缩包导出" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".zip";
String homeFolderPath = tempDir + zipName;
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(homeFolderPath));
String remoteFilePath="http://10.32.1.123/report/download/userReport/2/2023/07/14/729600323349381120/604527%E2%97%8F%E4%BC%8D%E4%BB%81%E5%8D%8E%E2%97%8F%E8%81%8C%E4%B8%9A%E5%81%A5%E5%BA%B7%E4%BD%93%E6%A3%80%E6%8A%A5%E5%91%8A.pdf";//StringZdyUtils.zwEncode2(path);
List<String> pathList=new ArrayList<>();
downloadFile1(remoteFilePath,tempDirFile.getAbsolutePath()+pdfName,zipOut);
}
/**
* 下载远程文件并保存到本地
*
* @param remoteFilePath-远程文件路径
* @param genPath-本地文件路径(带文件名)
*/
public static void downloadFile1(String remoteFilePath, String genPath,ZipOutputStream zipOut) {
URL urlfile = null;
HttpURLConnection httpUrl = null;
BufferedInputStream bis = null;
File f = new File(genPath);
try {
urlfile = new URL(remoteFilePath);
httpUrl = (HttpURLConnection) urlfile.openConnection();
httpUrl.connect();
bis = new BufferedInputStream(httpUrl.getInputStream());
ZipEntry zipEntry = new ZipEntry(f.getName());
// 将ZIP条目添加到ZIP文件
zipOut.putNextEntry(zipEntry);
// 从输入流读取数据并写入ZIP文件
byte[] bytes = new byte[1024];
int length;
while ((length = bis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
httpUrl.disconnect();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
zipOut.close();
bis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
private static void localDw() {
// 两个文件的路径
String file1Path = "C:\\Users\\Administrator\\Desktop\\新建文件夹\\path/file1.txt";
String file2Path = "C:\\Users\\Administrator\\Desktop\\新建文件夹\\path/file2.txt";
// ZIP文件的输出路径
String zipOutputPath = "C:\\Users\\Administrator\\Desktop\\新建文件夹\\path/output.zip";
try (FileOutputStream fos = new FileOutputStream(zipOutputPath);
ZipOutputStream zipOut = new ZipOutputStream(fos);
FileInputStream fis1 = new FileInputStream(file1Path);
FileInputStream fis2 = new FileInputStream(file2Path)) {
// 添加第一个文件到ZIP文件
addToZipFile(file1Path, fis1, zipOut);
// 添加第二个文件到ZIP文件
addToZipFile(file2Path, fis2, zipOut);
System.out.println("文件成功打包成ZIP文件!");
} catch (IOException e) {
e.printStackTrace();
}
}
private static void addToZipFile(String filePath, FileInputStream fis, ZipOutputStream zipOut)
throws IOException {
// 创建ZIP条目
ZipEntry zipEntry = new ZipEntry(new File(filePath).getName());
// 将ZIP条目添加到ZIP文件
zipOut.putNextEntry(zipEntry);
// 从输入流读取数据并写入ZIP文件
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
// 关闭当前ZIP条目
zipOut.closeEntry();
// 关闭输入流
fis.close();
}
/**
* 小试牛刀
* @param args
*/
public static void main(String[] args) {
/*远程文件路径*/
String remoteFilePath1 = "http://192.168.150.190:9000/reportfile/20230727/TJH24289_1.pdf";
//String remoteFilePath2 = "https://pic.3gbizhi.com/2019/1112/20191112013312648.jpg";
/*本地文件路径(带文件名)*/
String localFilePath1 ="C:\\Users\\Administrator\\Desktop\\biji\\广州塔.pdf";
//String localFilePath2 ="E:\\LeStoreDownload\\update\\大桥.jpg";
downloadFile1(remoteFilePath1,localFilePath1);
//downloadFile2(remoteFilePath2,localFilePath2);
}
}
FileUtil 工具类
于 2023-08-23 13:48:40 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)