public void getZipByFile(String filePath) {
File file = new File(filePath);
if (file.length() >= (1024 * 1024)) {
try {
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] buf = new byte[1024];
int len;
FileOutputStream fos = new FileOutputStream(file.getName()
+ ".zip");
BufferedOutputStream bos = new BufferedOutputStream(fos);
ZipOutputStream zos = new ZipOutputStream(bos);
ZipEntry ze = new ZipEntry(file.getName());// 压缩包里的文件名
zos.putNextEntry(ze);
while ((len = bis.read(buf)) != -1) {
zos.write(buf, 0, len);
zos.flush();
}
bis.close();
zos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
现在是成功实现了文件压缩,但是出现两个问题:1: 压缩后, 那个zip文件跑到eclipse的目录里了, 就是不知道怎么控制它的输出目录2: 打开压缩文件, 里面的文件名是乱码, 且无法解压缩解压缩的话, 就弹出了 winrara:诊断信息:
! D:\Program Files\eclipse\2011年10月100000.xml.zip: 无法创建 2011骞?0鏈?00000.xml
! 文件名、目录名或卷标语法不正确。
很急哇, 在线等哦.
乱码可能是中文引起的,先用纯英文验证一下,如果确实是这个问题,加个过滤流过滤一下
/**
* 进行压缩的工具方法
* @param in InputStream 需要进行压缩的输入流
* @param gzipout OutputStream 经过GZIP压缩后的输出流
*/
public static void compress(InputStream in, OutputStream gzipout) {
int read;
try {
GZIPOutputStream gout = new GZIPOutputStream(gzipout);
byte[] bytes = new byte[BUFFER];
while ((read = in.read(bytes, 0, BUFFER)) != -1) {
gout.write(bytes, 0, read);
gout.flush();
}
in.close();
gout.close();
} catch (Exception ex) {
ex.printStackTrace();
}
} /**
* 进行压缩的工具方法
* @param in InputStream 需要进行压缩的输入文件路径
* @param gzipout OutputStream 经过GZIP压缩后的输出文件路径
*/
public static void compress(String fileIn, String fileGzipout) throws
Exception {
try {
File inFile = new File(fileIn);
fileLength = inFile.length();
FileInputStream in = new FileInputStream(inFile);
FileOutputStream out = new FileOutputStream(fileGzipout);
compress(in, out);
try {
out.close();
} catch (IOException ex2) {
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}好了, 解决了, 没问题了.