在我的项目中,我正在提取rar文件。
我正在尝试归档到向用户显示提取进度(百分比),但进度总是以145%结束并且提取仍在运行而不是结束。
是否有可能使进度同步,如果提取完成则以100%结束?
提取代码:
public void extractArchive(File archive, File destination) throws RarException, IOException {
Archive arch;
InputStream ins;
final int BUFFER_SIZE = 4096;
byte[] buffer = new byte[BUFFER_SIZE];
long nread = 0L;
long length = archive.length();
int count;
try {
arch = new Archive(archive);
}
catch (RarException re) {
Log.e("Error", re.getMessage());
throw re;
}
catch (IOException ioe) {
Log.e("Error", ioe.getMessage());
throw ioe;
}
if (arch != null) {
if (arch.isEncrypted()) {
Log.e("Error", "Unsupported encrypted archive " + archive.getName());
try {
arch.close();
}
catch (Exception e) {
Log.e("Error", e.getMessage());
}
return;
}
else {
Log.w("RAR", "Extracting from " + archive.getName());
}
try {
FileHeader fh = null;
while (true) {
fh = arch.nextFileHeader();
ins = arch.getInputStream(fh);
if (fh == null) {
break;
}
String fileNameString = fh.getFileNameString();
if (fh.isEncrypted()) {
Log.e("Error", "Unsupported encrypted file " + fileNameString);
continue;
}
OutputStream stream = null;
try {
if (fh.isDirectory()) {
createDirectory(fh, destination);
}
else {
Log.w("RAR", "Extracting " + fileNameString);
File f = createFile(fh, destination);
while ((count = ins.read(buffer, 0, BUFFER_SIZE)) != -1) {
nread += count;
int progress = (int) ((nread * 100) / length);
sendRarProgress(progress);
}
stream = new FileOutputStream(f);
arch.extractFile(fh, stream);
}
}
catch (IOException ioe) {
Log.e("RAR", "Error extracting " + fileNameString, ioe);
throw ioe;
}
catch (RarException re) {
Log.e("RAR", "Error extracting " + fileNameString, re);
throw re;
}
finally {
try {
if (ins != null)
ins.close();
if (stream != null) {
stream.flush();
stream.close();
ins.close();
}
}
catch (Exception e) {
Log.e("RAR", "Error " + e);
}
}
}
}
finally {
try {
arch.close();
Log.w("RAR", "Extraction completed.");
Thread.sleep(1000); //Sleep for 1 second
archive.delete();
Log.v("RAR", "Archive: " + archive + " deleted.");
}
catch (Exception e) {
Log.e("Error", e.getMessage());
}
}
}
}