0

私はファイルを持っているとしましょうC:\source.dat。zipファイルに圧縮したいC:\folder\destination.zip

簡単な例を見つけることができず、Maven プロジェクトで提供されている HelloWorld は、平文ファイルを作成していないため、私の場合には実際には当てはまりません。誰かがこれについて教えてくれることを願っています。

参考までに、例で提供されているコードは次のとおりです。

@Override
protected int work(String[] args) throws IOException {
    // By default, ZIP files use character set IBM437 to encode entry names
    // whereas JAR files use UTF-8.
    // This can be changed by configuring the respective archive driver,
    // see Javadoc for TApplication.setup().
    final Writer writer = new TFileWriter(
            new TFile("archive.zip/dir/HälloWörld.txt"));
    try {
        writer.write("Hello world!\n");
    } finally {
        writer.close();
    }
    return 0;
}
4

2 に答える 2

1

これは簡単なことです。

使用する

1. ZipOutputStream -- Java のこのクラス このクラスは、ZIP ファイル形式でファイルを書き込むための出力ストリーム フィルタを実装します。圧縮されたエントリと圧縮されていないエントリの両方のサポートが含まれています。

公式ドキュメント

http://docs.oracle.com/javase/6/docs/api/java/util/zip/ZipOutputStream.html

2. ZipEntry -- このクラスは、ZIP ファイル エントリを表すために使用されます。

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/zip/ZipEntry.html

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ConverToZip {

    public static void main(String[] args) {
        // Take a buffer
        byte[] buffer = new byte[1024];

        try {

            // Create object of FileOutputStream

            FileOutputStream fos = new FileOutputStream("C:\\folder\\destination.zip.");

            // Get ZipOutstreamObject Object
            ZipOutputStream zos = new ZipOutputStream(fos);


            ZipEntry ze = new ZipEntry("source.dat");
            zos.putNextEntry(ze);
            FileInputStream in = new FileInputStream("C:\\source.dat");

            int len;
            while ((len = in .read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }

            in .close();
            zos.closeEntry();

            //remember close it
            zos.close();

            System.out.println("Done");

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
于 2013-04-19T03:38:31.547 に答える