public class DownloadUtils {
/**
* 从Url上下载文件并放到压缩包中
* @param filePath 可直接访问的文件路径 http或者https
* @param orgininalName 文件名
* @param out 压缩包输出流
* @throws IOException ioException
*/
public static void doZipForURLFile(String filePath, String orgininalName, ZipOutputStream out) throws IOException {
// 统一资源
URL url = new URL(filePath);
// 连接类的父类,抽象类
URLConnection urlConnection = url.openConnection();
// http的连接类
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
//设置超时
httpURLConnection.setConnectTimeout(1000 * 5);
//设置请求方式,默认是GET
httpURLConnection.setRequestMethod("GET");
// 设置字符编码
httpURLConnection.setRequestProperty("Charset", "UTF-8");
// 打开到此 URL引用的资源的通信链接(如果尚未建立这样的连接)。
httpURLConnection.connect();
ZipEntry entry = new ZipEntry(orgininalName);
out.putNextEntry(entry);
try (
InputStream ins = httpURLConnection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(ins)) {
byte[] buffer = new byte[1024];
int i = bis.read(buffer);
while (i != -1) {
out.write(buffer, 0, i);
out.flush();
i = bis.read(buffer);
}
}
out.closeEntry();
}
/**
* 下载 String 到压缩包中
* @param fileStr 字符串
* @param fileName 文件名称
* @param out ZipOutputStream
* @throws IOException IOException
*/
public static void doZipForStr(String fileStr, String fileName, ZipOutputStream out) throws IOException {
ZipEntry entry = new ZipEntry(fileName);
out.putNextEntry(entry);
try (
InputStream ins = new ByteArrayInputStream(fileStr.getBytes(StandardCharsets.UTF_8));
BufferedInputStream bis = new BufferedInputStream(ins)) {
byte[] buffer = new byte[1024];
int i = bis.read(buffer);
while (i != -1) {
out.write(buffer, 0, i);
out.flush();
i = bis.read(buffer);
}
}
out.closeEntry();
}
/**
* 字符串转文件
* @param content 字符串内容
* @param fileName 文件名称
* @param response 浏览器response
* @throws IOException ioException
*/
public static void strToFile(String content, String fileName, HttpServletResponse response) throws IOException {
InputStream fis = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
//定义文件输出流
OutputStream os = response.getOutputStream();
//设置头
FileUtils.setAttachmentResponseHeader(response, fileName);
//实现文件下载
byte[] buffer = new byte[1024];
int length = -1;
while ((length = fis.read(buffer))!= -1){
os.write(buffer,0,length);
}
//关闭输入输出流
fis.close();
os.close();
System.out.println(fileName + "下载成功!");
}
}
从Url上下载文件并放到压缩包中 * 下载 String 到压缩包中 * 字符串转文件,工具类
最新推荐文章于 2023-06-04 16:25:19 发布