0

現在、java.util.zipパッケージを使用してファイルを圧縮するプログラムを作成しています。それはうまく機能しますが、フォルダ/ディレクトリの圧縮はファイルの圧縮とは異なることに気づきました(間違っている場合は訂正してください)。私のプログラムでは、選択したファイルがフォルダーなのかファイル(.jpg、.png、.apkなど)なのかを知る必要があります。私は知ることができるようにいくつかの実験を試みました、そしてここに私のfilechooserアクティビティのサンプルコードがあります:( currentDirはファイルです)

    if(currentDir.isDirectory())Toast.makeText(this,"Directory",Toast.LENGTH_LONG).show();
    if(currentDir.isFile())Toast.makeText(this, "File", Toast.LENGTH_LONG).show();

これを挿入した後、アクティビティで選択したすべてのファイルは、画像を選択しても「ファイル」ではなく「ディレクトリ」を出力します。誰かがAndroidのファイルがフォルダであるかどうかを知る方法について私を助けてもらえますか?ありがとう!(最初の問題)

そして、前に言ったように、フォルダの圧縮はファイルの圧縮とは異なることに気づきました(間違っている場合は訂正/教えてください)。フォルダの圧縮に関してはすでに完了していますが、画像などのファイルの圧縮に関しては、ディレクトリを圧縮しますが、選択したファイルのみを圧縮する必要があると思います。これが私のサンプルコードです。(2番目の問題)

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

コメント、ヘルプ、提案、反応が必要であり、高く評価されます!ありがとう!

4

1 に答える 1

0
public void createZipFile(String path) {
        File dir = new File(path);
        String[] list = dir.list();
        String name = path.substring(path.lastIndexOf("/"), path.length());
        String _path;

        if(!dir.canRead() || !dir.canWrite())
            return;

        int len = list.length;

        if(path.charAt(path.length() -1) != '/')
            _path = path + "/";
        else
            _path = path;

        try {
            ZipOutputStream zip_out = new ZipOutputStream(
                                      new BufferedOutputStream(
                                      new FileOutputStream(_path + name + ".zip"), BUFFER));

            for (int i = 0; i < len; i++)
                zip_folder(new File(_path + list[i]), zip_out);

            zip_out.close();

        } catch (FileNotFoundException e) {
            Log.e("File not found", e.getMessage());

        } catch (IOException e) {
            Log.e("IOException", e.getMessage());
        }
    }

このコードを試してください。

于 2012-05-22T12:04:57.903 に答える