Java 如何加载驻留在S3 bucket中的zip文件?
我有一种情况,需要打开驻留在S3 bucket中的zip文件。 到目前为止,我的代码如下所示:Java 如何加载驻留在S3 bucket中的zip文件?,java,amazon-s3,Java,Amazon S3,我有一种情况,需要打开驻留在S3 bucket中的zip文件。 到目前为止,我的代码如下所示: public ZipFile readZipFile(String name) throws Exception { GetObjectRequest req = new GetObjectRequest(settings.getAwsS3BatchRecogInBucketName(), name); S3Object obj = s3Client.getObject(req);
public ZipFile readZipFile(String name) throws Exception {
GetObjectRequest req = new GetObjectRequest(settings.getAwsS3BatchRecogInBucketName(), name);
S3Object obj = s3Client.getObject(req);
S3ObjectInputStream is = obj.getObjectContent();
/******************************
* HOW TO DO
******************************/
return null;
}
public ZipFile readZipFile(String name) throws Exception {
GetObjectRequest req = new GetObjectRequest(settings.getAwsS3BatchRecogInBucketName(), name);
S3Object obj = s3Client.getObject(req);
S3ObjectInputStream is = obj.getObjectContent();
File temp = File.createTempFile(name, "");
temp.setWritable(true);
FileOutputStream fos = new FileOutputStream(temp);
fos.write(IOUtils.toByteArray(is));
fos.flush();
return new ZipFile(temp);
}
以前我确实尝试过创建一个临时文件对象,并使用file.createTempFile函数,但我总是在没有创建文件对象的地方遇到麻烦。我之前的尝试如下所示:
public ZipFile readZipFile(String name) throws Exception {
GetObjectRequest req = new GetObjectRequest(settings.getAwsS3BatchRecogInBucketName(), name);
S3Object obj = s3Client.getObject(req);
S3ObjectInputStream is = obj.getObjectContent();
/******************************
* HOW TO DO
******************************/
return null;
}
public ZipFile readZipFile(String name) throws Exception {
GetObjectRequest req = new GetObjectRequest(settings.getAwsS3BatchRecogInBucketName(), name);
S3Object obj = s3Client.getObject(req);
S3ObjectInputStream is = obj.getObjectContent();
File temp = File.createTempFile(name, "");
temp.setWritable(true);
FileOutputStream fos = new FileOutputStream(temp);
fos.write(IOUtils.toByteArray(is));
fos.flush();
return new ZipFile(temp);
}
有人遇到过这种情况吗?请告诉我谢谢:)如果您想立即使用zip文件而不首先将其保存到临时文件,您可以使用
java.util.zip.ZipInputStream
:
import java.util.zip.ZipInputStream;
S3ObjectInputStream is = obj.getObjectContent();
ZipInputStream zis = new ZipInputStream(is);
从这里开始,您可以通读zip文件的条目,忽略不需要的条目,并使用需要的条目:
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
String name = entry.getName();
if (iWantToProcessThisEntry(name)) {
processFile(name, zis);
}
zis.closeEntry();
}
public void processFile(String name, InputStream in) throws IOException { /* ... */ }
您不必担心以这种方式存储临时文件