Android Zip文件

时间:2015-06-02 05:40:12

标签: java android file zip

我试过搜索答案,但找不到答案,所以我发帖了。我正在尝试压缩文件,并按照this link,我能够这样做。问题是,在这个例子中,文件名和文件路径是硬编码的。所以我尝试根据需要更改代码库。

原始代码:

   // .... 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

1 个答案:

答案 0 :(得分:0)

让我给出一个简单的代码,用于创建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();
    }
}