不使用BufferedOutputStream
的情况
引入读取输入流,并不知道会读多少字节数据,如果将byte数组设的过大,会造成存在很多空字符,并且写入到文件中,所以使用大小为1的数组长度最保稳
public class UnzipFile {
private static File file;
private static FileInputStream fileInputStream;
private static BufferedInputStream bufferedInputStream;
private static ZipInputStream zipInputStream;
private static ZipEntry zipEntry;
private static String OUTPUT_FILE_PAHT;
private static FileOutputStream fileOutputStream;
private static BufferedOutputStream bufferedOutputStream;
public static void TestUzipFile(String file_path) {
UzipFile(file_path);
}
/*
* @param filepath 需要解压的文件的路径
*
*/
private static void UzipFile(String filepath) {
OUTPUT_FILE_PAHT = System.getProperty("user.dir") + "\\AndroidManifest.xml";
try {
//获取压缩包输入流
fileInputStream = new FileInputStream(new File(filepath));
zipInputStream = new ZipInputStream(fileInputStream);
while((zipEntry = zipInputStream.getNextEntry()) != null) {
String fileName = zipEntry.getName();
if(fileName.equals("AndroidManifest.xml")) {
fileOutputStream = new FileOutputStream(OUTPUT_FILE_PAHT);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
byte[] bt = new byte[1];
while(zipInputStream.read(bt) != -1) {
//解压文件到本地
fileOutputStream.write(bt);
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
fileOutputStream.close();
zipInputStream.close();
fileInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
正常解压代码:
public static void TestUzipFile(String file_path) {
UzipFile(file_path);
}
/*
* @param filepath 需要解压的文件的路径
*
*/
private static void UzipFile(String filepath) {
OUTPUT_FILE_PAHT = System.getProperty("user.dir") + "\\AndroidManifest.xml";
try {
//获取压缩包输入流
fileInputStream = new FileInputStream(new File(filepath));
bufferedInputStream = new BufferedInputStream(fileInputStream);
zipInputStream = new ZipInputStream(bufferedInputStream);
while((zipEntry = zipInputStream.getNextEntry()) != null) {
String fileName = zipEntry.getName();
if(fileName.equals("AndroidManifest.xml")) {
System.out.println(OUTPUT_FILE_PAHT);
fileOutputStream = new FileOutputStream(OUTPUT_FILE_PAHT);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
int buff_size;
while((buff_size=zipInputStream.read()) != -1) {
//解压文件到本地
bufferedOutputStream.write(buff_size);
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
bufferedOutputStream.close();
fileOutputStream.close();
zipInputStream.close();
fileInputStream.close();
bufferedInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
网友评论