Android Zip Files



我试着寻找答案,但找不到任何,所以我张贴。我正在尝试压缩文件,并通过以下链接,我能够做到这一点。问题是,在这个示例中,文件名和文件路径是硬编码的。所以我试着根据我的需要来改变代码库。

原始代码:

   // .... additional codes here  
   String inputPath = Environment.getExternalStorageDirectory().getPath()+ "/TextFiles/";
   String inputFile = "MyZippedFiles.zip";

   ((Button) findViewById(R.id.button_zip))
   .setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                // declare an array for storing the files i.e the path of your source files
                s[0] = inputPath + "/01.txt";
                s[1] = inputPath + "/02.txt";
                /** 
                 * first parameter is the files, second parameter is zip file name 
                 * then call the zip function
                 */
                ZipManager zipManager = new ZipManager();
                zipManager.zip(s, inputPath + inputFile);
            }
        });

ZipManager.java:

public class ZipManager {
    private static final int BUFFER = 80000;
    public void zip(String[] _files, String zipFileName) {
        try {
            BufferedInputStream origin = null;
            FileOutputStream dest = new FileOutputStream(zipFileName);
            ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
                    dest));
            byte data[] = new byte[BUFFER];
            for (int i = 0; i < _files.length; i++) {
                Log.v("Compress", "Adding: " + _files[i]);
                FileInputStream fi = new FileInputStream(_files[i]);
                origin = new BufferedInputStream(fi, BUFFER);
                ZipEntry entry = new ZipEntry(_files[i].substring(_files[i].lastIndexOf("/") + 1));
                out.putNextEntry(entry);
                int count;
                while ((count = origin.read(data, 0, BUFFER)) != -1) {
                    out.write(data, 0, count);
                }
                origin.close();
            }
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

同样,这段代码工作得很好,但是文件名被硬编码了。所以,我修改了代码来解决我的问题。

新代码:

        ((Button) findViewById(R.id.button_zip))
        .setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                // declare an array for storing the files i.e the path of your source files
                String[] s = dir.list(txtFilter);
                for (String filename : s) {
                    String path = dir.getAbsolutePath() + "/" + filename;
                    Log.v("TEST", path);
                    ZipManager zipManager = new ZipManager();
                    zipManager.zip(path, inputPath + inputFile);
                }
            }
        });
//FilefilterName method :
public FilenameFilter txtFilter = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String filename) {
            return filename.endsWith(".txt") || filename.endsWith(".TXT");
        }
    };

ZipManager.java:

public class ZipManager {
    private static final int BUFFER = 80000;
    public void zip(String path, String zipFileName) {
        try {
            BufferedInputStream origin = null;
            FileOutputStream dest = new FileOutputStream(zipFileName);
            ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
            byte data[] = new byte[BUFFER];
            for (int i = 0; i < path.length(); i++) {
                Log.v("Compress", "Adding: " + path);
                FileInputStream fi = new FileInputStream(path);
                origin = new BufferedInputStream(fi, BUFFER);
                ZipEntry entry = new ZipEntry(path.substring(path.lastIndexOf("/") + 1));
                out.putNextEntry(entry);
                int count;
                while ((count = origin.read(data, 0, BUFFER)) != -1) {
                    out.write(data, 0, count);
                }
                origin.close();
            }
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

LOGCAT:

       TEST          /storage/sdcard/TextFiles/01.txt
       Compress      Adding: /storage/sdcard/TextFiles/01.txt
       TEST          /storage/sdcard/TextFiles/02.txt
       Compress      Adding: /storage/sdcard/TextFiles/02.txt

问题:

它正在创建压缩文件MyZippedFiles.zip,问题是,它不包含任何内容。文件大小为0。应该做些什么?TIA

让我给出一个简单的代码来创建selectedFiles的zip文件

@Override
public void onClick(View view) {
                File zipFile = new File(getFilesDir(), "zipImages.zip");
                try {
                    FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
                    zipFiles(imageFiles, fileOutputStream);
                    //Do whatever you want to do with zipFile
                     //for example
                     sendZipfile(zipFile);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
}
public void zipFiles(List<File> fileList, OutputStream os) throws IOException {
    ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(os));
    try {
        for (int i = 0; i < fileList.size(); ++i) {
            File file = fileList.get(i);
            String filename = file.getName();
            byte[] bytes = readFile(file);
            ZipEntry entry = new ZipEntry(filename);
            zos.putNextEntry(entry);
            zos.write(bytes);
            zos.closeEntry();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        zos.close();
    }
}
public static byte[] readFile(File file) throws IOException {
    // Open file
    RandomAccessFile f = new RandomAccessFile(file, "r");
    try {
        // Get and check length
        long longlength = f.length();
        int length = (int) longlength;
        if (length != longlength)
            throw new IOException("File size >= 2 GB");
        // Read file and return data
        byte[] data = new byte[length];
        f.readFully(data);
        return data;
    } finally {
        f.close();
    }
}

相关内容

  • 没有找到相关文章

最新更新