2

URLから.zipファイルをダウンロードし、各ファイルを.zipファイルからバイト配列に変換するアプリケーションがあります。現時点では、ファイルをダウンロードして .zip ファイルを読み取り、.zip ファイル全体をバイトに変換できますが、.zip 内の各ファイルをバイト配列に変換することに失敗しました。どんな助けでも感謝します。以下にコードを添付しました。

try {
    URL url = new URL(Url);
    //create the new connection
    HttpURLConnection urlConnection = (HttpURLConnection)                                url.openConnection();

    //set up some things on the connection
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoOutput(true); 
    //and connect!
    urlConnection.connect();
    //set the path where we want to save the file
    //in this case, going to save it on the root directory of the
    //sd card.
    InputStream inputStream = urlConnection.getInputStream();
    dis = new DataInputStream(new BufferedInputStream(inputStream));
    System.out.println("INput connection done>>>>>");

    zis = new ZipInputStream(new BufferedInputStream(dis));

    String targetFolder="/sdcard/";

    System.out.println("zip available is"+zis.available());

    int extracted = 0;

    while ((entry = zis.getNextEntry()) != null) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int count;

        while ((count = zis.read(buffer)) != -1) {
            baos.write(buffer, 0, count);
        }

        String filename = entry.getName();
        System.out.println("File name is>>"+filename);

        byte[] bytes = baos.toByteArray();
        System.out.println("Bytes is >>>>"+bytes.toString());
        // do something with 'filename' and 'bytes'...
        zis.closeEntry();

        extracted ++;
    }

    zis.close();

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
4

2 に答える 2

1

while ((count = zis.read(buffer)) != -1)は、zipファイル全体の読み取りをループします。あなたがしたいのはですcount = zis.read(buffer, 0, entry.getSize())。これにより、すべて1つのコマンドで、各zipファイルエントリの内容がバッファにダンプされます。

そして、そのバイト配列をもっと大きくしたいと思うでしょう。

または、小さなバッファを保持することもできますが、メインループの反復ごとに、entry.getSize()バイトのみを読み取るようにしてください。そうしないと、ファイル全体が読み取られることになります。

于 2011-08-26T14:41:13.223 に答える
0

Jon7 の回答に基づいて (これで問題が解決した場合、誰が本当にクレジットを取得する必要があります)、これを試してください:

while ((entry = zis.getNextEntry()) != null) {
    String filename = entry.getName();
    int needed = entry.getSize();
    byte[] bytes = new byte[needed];
    int pos = 0;
    while (needed > 0) {
        int read = zis.read(bytes, pos, needed);
        if (read == -1) {
            // end of stream -- OOPS!
            throw new IOException("Unexpected end of stream after " + pos + " bytes for entry " + filename);
        }
        pos += read;
        needed -= read;
    }

    System.out.println("File name is>>"+filename);
    System.out.println("Bytes is >>>>"+bytes.toString());
    // do something with 'filename' and 'bytes'...
    zis.closeEntry();

    extracted ++;
}
于 2011-08-26T15:00:30.970 に答える