- 41
- 0
问题描述
java中,根据url下载文件,然后压缩文件,解压出错,但是,如果此时将压缩文件删除掉,然后重新运行程序,再解压文件,结果能够成功解压。
问题出现的环境背景及自己尝试过哪些方法
检查程序,不知道哪里出问题了。
相关代码
// 请把代码文本粘贴到下方(请勿用图片代替代码)
源代码如下:
import com.jd.eptid.waremanager.common.tools.DateUtils;
import com.jd.eptid.waremanager.common.tools.DownloadUtil;
import java.io.IOException;
import java.util.Date;
public class MyTest {
public static void main(String args[]) throws IOException, InterruptedException {
final String targetFolderPath = "/Users/cdshilejian/Desktop/img/";
final String newZipFilePath = "/Users/cdshilejian/Desktop/new_" + DateUtils.format(new Date()) + ".zip";
final String[] urls = {
"http://e.hiphotos.baidu.com/image/pic/item/2f738bd4b31c8701ad467c1a2b7f9e2f0608ff5e.jpg",
"http://e.hiphotos.baidu.com/image/pic/item/2f738bd4b31c8701ad467c1a2b7f9e2f0608ff5e.jpg",
"http://e.hiphotos.baidu.com/image/pic/item/2f738bd4b31c8701ad467c1a2b7f9e2f0608ff5e.jpg",
"http://e.hiphotos.baidu.com/image/pic/item/2f738bd4b31c8701ad467c1a2b7f9e2f0608ff5e.jpg",
"http://e.hiphotos.baidu.com/image/pic/item/2f738bd4b31c8701ad467c1a2b7f9e2f0608ff5e.jpg",
"http://e.hiphotos.baidu.com/image/pic/item/2f738bd4b31c8701ad467c1a2b7f9e2f0608ff5e.jpg"};
DownloadUtil.downLoadToCompressFile(urls, targetFolderPath,newZipFilePath);
}
}
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class DownloadUtil extends Thread {
public volatile static boolean exit = false;
//此方法实现文件夹的删除
public static void deleteAllFilesOfDir(File path) {
if (!path.exists())
return;
if (path.isFile()) {
path.delete();
return;
}
File[] files = path.listFiles();
for (int i = 0; i < files.length; i++) {
deleteAllFilesOfDir(files[i]);
System.out.println("删除图片" + files[i]);
}
path.delete();
}
//此方法实现图片下载
public static void download(String url,
String string,
String fname,
int skuId,
int index) throws IOException {
// TODO Auto-generated method stub
URL u = new URL(url);
URLConnection con = u.openConnection();
System.out.println("开始下载第" + index + " 图片");
try {
con.setConnectTimeout(20 * 1000);
con.setReadTimeout(10 * 1000);
} catch (Exception e) {
System.out.println("第" + index + "下载失败");
}
try {
InputStream is = con.getInputStream();
byte[] bs = new byte[1024];
int len;
File sf = new File(fname + skuId);
if (!sf.exists()) {
sf.mkdir();
}
OutputStream os = new FileOutputStream(sf.getPath() + '/' + string);
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
System.out.println("下载第" + index + "图片完成");
os.close();
is.close();
} catch (Exception e) {
// TODO: handle exception
}
}
//此方法实现文件夹得创建
public static boolean createDir(String fname) {
File dir = new File(fname);
if (dir.exists()) {
return false;
}
// 判断字符串是否以‘/’作为分隔符
if (!fname.endsWith(File.separator))
fname = fname + File.separator;
// 创建单个目录
return dir.mkdirs() ? true : false;
}
static final int BUFFER = 8192;
public static void compress(String srcPath , String dstPath) throws IOException{
File srcFile = new File(srcPath);
File dstFile = new File(dstPath);
if (!srcFile.exists()) {
throw new FileNotFoundException(srcPath + "不存在!");
}
FileOutputStream out = null;
ZipOutputStream zipOut = null;
try {
out = new FileOutputStream(dstFile);
CheckedOutputStream cos = new CheckedOutputStream(out, new CRC32());
zipOut = new ZipOutputStream(cos);
String baseDir = "";
compress(srcFile, zipOut, baseDir);
}
finally {
if(null != zipOut){
zipOut.close();
out = null;
}
if(null != out){
out.close();
}
}
}
private static void compress(File file, ZipOutputStream zipOut, String baseDir) throws IOException{
if (file.isDirectory()) {
compressDirectory(file, zipOut, baseDir);
} else {
compressFile(file, zipOut, baseDir);
}
}
/** 压缩一个目录 */
private static void compressDirectory(File dir, ZipOutputStream zipOut, String baseDir) throws IOException{
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
compress(files[i], zipOut, baseDir + dir.getName() + "/");
}
}
/** 压缩一个文件 */
private static void compressFile(File file, ZipOutputStream zipOut, String baseDir) throws IOException{
if (!file.exists()){
return;
}
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(new FileInputStream(file));
ZipEntry entry = new ZipEntry(baseDir + file.getName());
zipOut.putNextEntry(entry);
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
zipOut.write(data, 0, count);
}
}finally {
if(null != bis){
bis.close();
}
}
}
/**
*下载并压缩文件
*/
public static void downLoadToCompressFile(String[] picUrls, String fname, String newZipFilePath) throws IOException, InterruptedException {
final String targetFolderPath = fname;
final String[] url = picUrls;
DownloadUtil.createDir(targetFolderPath);
ExecutorService pool = Executors.newFixedThreadPool(6);
for (int i = 0; i < picUrls.length; i++) {
final int index = i;
pool.execute(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
// 此方法实现图片的下载
String[] arr = url[index].split("\\.");
String suffix = arr[arr.length - 1];
DownloadUtil.download(url[index], index + "." + suffix, targetFolderPath, 1, index);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
//将目标目录的文件压缩成zip文件
compress(targetFolderPath , newZipFilePath);
DownloadUtil.sleep(5000);
DownloadUtil.exit = true;
// File file = new File(fname);
// DownloadUtil.deleteAllFilesOfDir(file);
}
}
你期待的结果是什么?实际看到的错误信息又是什么?
能够正确解压文件
- 共 0 条
- 全部回答
-
招人烦°惹人厌 普通会员 1楼
在Java中,我们可以使用Apache HttpClient库来下载文件并压缩文件。以下是一个简单的示例,展示如何使用Apache HttpClient下载文件并压缩文件:
```java import org.apache.http.HttpResponse; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients;
public class Main { public static void main(String[] args) { try { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://example.com/file.zip"); HttpResponse response = httpClient.execute(httpGet); System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity(); if (entity != null) { byte[] bytes = entity.getContent(); // 使用Apache Commons Compress库来压缩文件 CompressFileUtils comprUtil = new CompressFileUtils(bytes); comprUtil.save("file.zip"); } } catch (Exception e) { e.printStackTrace(); } }} ```
在这个示例中,我们首先创建一个
CloseableHttpClient对象,然后创建一个HttpGet对象来获取文件。然后,我们调用execute方法来执行请求,并获取响应。然后,我们获取响应的
entity对象。如果entity对象不为null,我们就使用Apache Commons Compress库来压缩文件。最后,我们将压缩后的文件保存到file.zip。注意:这个示例假设你已经安装了Apache Commons Compress库,并且你已经添加了它的依赖到你的项目中。如果你还没有安装这个库,你可以使用以下命令来安装它:
bash mvn install:install-file如果你的项目使用的是Maven,你可以使用以下命令来安装这个库:
bash mvn dependency:tree然后,你可以使用以下命令来安装Apache Commons Compress库:
bash mvn install:install-file -DgroupId=com.example -DartifactId=compresser -Dversion=1.0.0 -Dpackaging=jar
- 扫一扫访问手机版
回答动态

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器更新之后。服务器里面有部分玩家要重新创建角色是怎么回事啊?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题函数计算不同地域的是不能用内网吧?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题ARMS可以创建多个应用嘛?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题在ARMS如何申请加入公测呀?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题前端小程序接入这个arms具体是如何接入监控的,这个init方法在哪里进行添加?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器刚到期,是不是就不能再导出存档了呢?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器的游戏版本不兼容 尝试更新怎么解决?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器服务器升级以后 就链接不上了,怎么办?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器转移以后服务器进不去了,怎么解决?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器修改参数后游戏进入不了,是什么情况?预计能赚取 0积分收益
- 回到顶部
- 回到顶部

