Javaでzipフォルダを読み込む方法は何ですか?
Javaでzipフォルダを読み込むには、ZipInputStreamクラスを使用することができます。以下は、zipフォルダ内のすべてのファイルを読み込む方法を示す簡単なサンプルコードです。
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class ReadZipFolder {
public static void main(String[] args) {
try {
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream("path/to/your/zipfile.zip"));
ZipEntry entry = zipInputStream.getNextEntry();
while (entry != null) {
if (!entry.isDirectory()) {
System.out.println("File: " + entry.getName());
// 读取文件内容
byte[] buffer = new byte[1024];
int bytesRead;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
while ((bytesRead = zipInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("Content: " + new String(outputStream.toByteArray()));
outputStream.close();
}
entry = zipInputStream.getNextEntry();
}
zipInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
この例では、まずZipInputStreamオブジェクトを作成し、読み取りたいZIPファイルを渡します。次に、getNextEntry()メソッドを使用して、ZIPファイル内のファイルを1つずつ読み取り、それぞれのエントリがフォルダーかどうかを確認します。フォルダーでない場合は、ファイルの内容を読み取って出力します。
注意してください、これは単なる簡単なサンプルコードであり、実際に使用する際には例外処理やさまざまな状況に対応するための追加のロジックが必要になるかもしれません。