Read the Zip file and convert it directly to a string.
The readAllBytes method of the InputStream class is used for reading. It's very convenient because it reads all the bytes at once.
However, according to the reference, "Note that this method is used in a simple case where it is convenient to read all the bytes into one byte array, because it reads an input stream with a large amount of data. It is not the one. "
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 = "Specify the Zip file path here";
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(filePath)));
//Repeat as long as there is a file in the zip file
while(zis.getNextEntry() !=null){
String str = new String(zis.readAllBytes());
//Output for the time being
System.out.println(str);
}
zis.close();
}
}
For reference, I'll also include the code to read little by little.
Sample.java
String filePath = "Specify the path of the Zip file to read here";
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(filePath)));
String str = null;
byte[] tempBuffer = new byte[1024];//Number of bytes to read at one time
ByteArrayOutputStream streamBuilder = null;
int bytesRead;
//Repeat as long as there is a file in the zip file
while(zis.getNextEntry() !=null){
while ( (bytesRead = zis.read(tempBuffer)) != -1 ){
streamBuilder = new ByteArrayOutputStream();
streamBuilder.write(tempBuffer, 0, bytesRead);
}
//Convert to String
str = streamBuilder.toString("UTF-8");
System.out.println(str);
}
zis.close();
Recommended Posts