Ps:最近一有空就抽时间捞以前一些用过的但是没记录的小技能。
/**
* 获取zipfile大小
* @param path
* @return
*/
public static long getZipFileSize(File path) {
long size = 0;
ZipFile mZipFile = null;
try {
mZipFile = new ZipFile(path);
Enumeration<? extends ZipEntry> enumeration = mZipFile.entries();
while (enumeration.hasMoreElements()) {
size += enumeration.nextElement().getSize();
}
} catch (IOException e) {
e.printStackTrace();
}
return size;
}
/**
* 解压
* @param inputPath
* @param outputPath
*/
public static void unZipFile(Activity mActivity, String inputPath, String outputPath) {
long inPathFileSize = getZipFileSize(new File(inputPath));
try {
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(inputPath));
if (zipInputStream == null || zipInputStream.available() == 0) {
showToast("Zip File Error");
return;
}
String pathFileName;
ZipEntry mEntry;
while ((mEntry = zipInputStream.getNextEntry()) != null) {
pathFileName = mEntry.getName();
String currentPathName = "";
if (mEntry.isDirectory()) {
pathFileName = pathFileName.substring(0, pathFileName.length() - 1);
currentPathName = outputPath + File.separator + pathFileName;
new File(currentPathName).mkdirs();
} else {
File file = new File(outputPath + "/" + pathFileName);
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
FileOutputStream outputStream = new FileOutputStream(file);
int len;
long count = 0;
byte[] buffer = new byte[1024];
while ((len = zipInputStream.read(buffer)) != -1) {
count += len;
final int progress = (int) ((count * 100) / inPathFileSize);
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Log.e("progress", "progress: " + progress);
}
});
outputStream.write(buffer, 0, len);
outputStream.flush();
}
outputStream.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/***
* 读取文件
* @param path
* @return
*/
public static String readFileContent(String path) {
File file = new File(path);
StringBuffer stringBuffer = new StringBuffer();
if (!file.exists()) {
showToast("文件不存在!");
} else {
try {
InputStream inputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return stringBuffer.toString();
}
自我感觉注释还是很清楚的,第三个方法是附带的,自己写demo的时候肯定要读取个文件试试,解压的时候一般都是伴随着进度条的显示,由于是耗时操作,需要开一个线程使用。可以写一个接口去设置进度,如果存在错误请及时指出,谢谢。