1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

<java>Zipファイルを読み込み直接文字列に変換する

Last updated at Posted at 2020-09-12

概要

Zipファイルを読み込み直接文字列に変換します。

解説

読み込みにはInputStreamクラスのreadAllBytesメソッドを使用しています。
すべてのバイトを一気に読み込んでくれるのでとても便利ですね~。

ただしリファレンスによると、「このメソッドが、すべてのバイトを1つのバイト配列に読み取ると都合が良い簡単なケースで使用するものであることに注意してください。 大量のデータを持つ入力ストリームを読み込むためのものではありません。」という記載がありました。

コード

Unzip.java

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.util.zip.ZipInputStream;

public class Unzip{
	public static void main(String[] args) throws Exception {

		String filePath = "ここでZipファイルのパスを指定";

		ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(filePath)));

		//zipファイルの中にファイルがあるだけ繰り返す
		while(zis.getNextEntry() !=null){

			String str = new String(zis.readAllBytes());

			//とりあえず出力しておく
			System.out.println(str);
		}
		zis.close();
	}
}


参考

参考までに、少しずつ読み込むコードも載せておきます。

Sample.java
		String filePath = "ここで読み込むZipファイルのパスを指定します";

		ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(filePath)));


		String str = null;
		byte[] tempBuffer = new byte[1024];//一度に読み込むバイト数
		ByteArrayOutputStream streamBuilder = null;
		int bytesRead;

		//zipファイルの中にファイルがあるだけ繰り返す
		while(zis.getNextEntry() !=null){
			while ( (bytesRead = zis.read(tempBuffer)) != -1 ){

				streamBuilder = new ByteArrayOutputStream();
				streamBuilder.write(tempBuffer, 0, bytesRead);

			}
           //Stringに変換する
			str = streamBuilder.toString("UTF-8");
			System.out.println(str);
		}
		zis.close();
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?