java - Android 压缩文件

标签 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();
        }
    }

日志:

       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();
    }
}

关于java - Android 压缩文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30588169/

相关文章:

java - A* 算法 8 谜题

java - 静态 InetAddress.getLoopbackAddress() 返回什么?

c# - 使用密码中的随机数字进行身份验证

c++ - 将大文件读入字符数组的正确方法

c - 搜索文件中的元素并打印整行

java - jodatime javadoc 文档未显示在 Android Studio 中

java - Android SDK - Java - listview.setAdapter 失败

java - 无法以编程方式连接到蓝牙设备

java - 如何将数据从 Activity 或 fragment 传递到 View 模型?

java - 在 Java 中持久化配置的最合适方法是什么?