I m currently creating a program that compresses a file by using java.util.zip package. It works well but I noticed that compressing a folder/directory is different from compressing a file (correct me if I m wrong). In my program, I have to know whether a selected file is a folder or a file(such as .jpg, .png, .apk and etc). I ve tried some experiments for me to be able to know and here is the sample code in my filechooser activity : (currentDir is a File)
if(currentDir.isDirectory())Toast.makeText(this,"Directory",Toast.LENGTH_LONG).show();
if(currentDir.isFile())Toast.makeText(this, "File", Toast.LENGTH_LONG).show();
在此插入之后, 在我的活动中选择的每一个文件都会输出一个“ 日志” 而不是一个“ 文件 ”, 即使我选择了一个图像 。 有人能帮助我了解一个文件是否是一个文件夹吗? 谢谢! (第一个问题是)
正如我先前说过的,我注意到压缩一个文件夹与压缩一个文件不同(更正/如果我错了,就教给我)。关于压缩一个文件夹,我已经做了。但在压缩一个文件,如图像等,它仍然压缩目录,但我相信,只压缩我所选择的文件。这是我的样本代码。 (第二个问题)
public void onClick(View v) {
try{
ZipOutputStream zos = new ZipOutputStream( new FileOutputStream(new File(currentDir.getPath()+".zip")) );
zip( currentDir, currentDir, zos );
zos.close();
Toast.makeText(this, "File successfully compressed!", Toast.LENGTH_LONG).show();
}catch (IOException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();}
}
private static final void zip(File directory, File base,ZipOutputStream zos) throws IOException {
File[] files = directory.listFiles();
byte[] buffer = new byte[8192];
int read = 0;
for (int i = 0, n = files.length; i < n; i++) {
if (files[i].isDirectory()) {
zip(files[i], base, zos);
} else {
FileInputStream in = new FileInputStream(files[i]);
ZipEntry entry = new ZipEntry(files[i].getPath().substring(base.getPath().length() + 1));
zos.putNextEntry(entry);
while (-1 != (read = in.read(buffer))) {
zos.write(buffer, 0, read);
}
in.close();
}
}
}
任何评论、帮助、建议、反应都是需要的,