- 使用IO写ZIP之后导致ZIP文件无法读取
获取到ZIP文件的InputStream之后通过DataOutoutStream写入到文件,写完之后再使用ZipFile读取时报无法打开zip文件
实现代码:
public static String writeZip(String path,String fileName,InputStream in) {
String str = “”;
if(StringUtils.isEmpty(path))
throw new NullPointerException(“file path is null.”);
if(StringUtils.isEmpty(fileName))
throw new NullPointerException(“file name is null.”);
String filePath = path + File.separator + fileName;
DataOutputStream out = null;
try {
out = new DataOutputStream(new FileOutputStream(filePath));
byte [] b = new byte[1024];
int readCount = in.read(b);
while(readCount > -1) {
out.write(b);
readCount = in.read(b);
}
str = new String(b,“UTF-8”);
logger.info("ca receive data : " + str);
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return str;
}
上面文件的写入方式存在一个bug,当文件大小不是1024的整数倍时会导致数组中多余的null字节也会写入文件,最终导致文件原始内容被破坏导致无法读取zip文件
解决方法:
public static String writeZip(String path,String fileName,InputStream in) {
String str = “”;
if(StringUtils.isEmpty(path))
throw new NullPointerException(“file path is null.”);
if(StringUtils.isEmpty(fileName))
throw new NullPointerException(“file name is null.”);
String filePath = path + File.separator + fileName;
DataOutputStream out = null;
try {
out = new DataOutputStream(new FileOutputStream(filePath));
byte [] b = new byte[1024];
int readCount = in.read(b);
while(readCount > -1) {
if(readCount < 1024) {
byte [] temp = new byte[readCount];
System.arraycopy(b, 0, temp, 0, readCount);
out.write(temp);
}else {
out.write(b);
}
readCount = in.read(b);
}
str = new String(b,“UTF-8”);
logger.info("ca receive data : " + str);
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(out != null) {
try {
out.close();
} catch (IOE