如何从 Amazon S3 存储桶内的文件夹中获取 PDF 文件
我是 AWS 和 S3 with Java 的新手,我想从 s3 存储桶中获取一个对象,该对象是存储桶中文件夹内的 pdf 文件。我已成功从 s3 存储桶获取文件,但在尝试从文件夹获取文件时遇到文件未找到异常
。
这是我的代码 -
public static void main(String[] args) {
System.out.println("Fetching pdf from aws s3");
String bucket = "my-bucket";
String key = "65/65-abc.pdf";
AmazonS3 amazonS3 = getAmazonS3Client();
S3Object object = amazonS3.getObject(new GetObjectRequest(bucket, key));
InputStream ins = object.getObjectContent();
try {
PDDocument doc = PDDocument.load(ins);
//Saving the document
doc.save(key);
System.out.println("PDF created");
}
catch (Exception e){
System.out.println(e);
}
}
private static AmazonS3 getAmazonS3Client(){
AWSCredentials awsCredentials = new BasicAWSCredentials("myAccessKey", "mySecretKey");
return AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
.withRegion(Regions.US_EAST_2).build();
}
输出 -
java.io.FileNotFoundException: 65\65-abc.pdf (The system cannot find the path specified)
我的 S3 存储桶结构类似于 -
my-bucket/65/65-abc.pdf
my-bucket
= 是存储桶名称 65
= 是文件夹名称 65-abc.pdf
= 是文件名
I am new to AWS and S3 with Java I want to fetch an object from the s3 bucket which is a pdf file that is inside of a folder in the bucket. I have successfully fetched the file from s3 bucket, but I am getting file not found exception
while trying to get the file from a folder.
Here is my code-
public static void main(String[] args) {
System.out.println("Fetching pdf from aws s3");
String bucket = "my-bucket";
String key = "65/65-abc.pdf";
AmazonS3 amazonS3 = getAmazonS3Client();
S3Object object = amazonS3.getObject(new GetObjectRequest(bucket, key));
InputStream ins = object.getObjectContent();
try {
PDDocument doc = PDDocument.load(ins);
//Saving the document
doc.save(key);
System.out.println("PDF created");
}
catch (Exception e){
System.out.println(e);
}
}
private static AmazonS3 getAmazonS3Client(){
AWSCredentials awsCredentials = new BasicAWSCredentials("myAccessKey", "mySecretKey");
return AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
.withRegion(Regions.US_EAST_2).build();
}
Output-
java.io.FileNotFoundException: 65\65-abc.pdf (The system cannot find the path specified)
My S3 bucket structure is like -
my-bucket/65/65-abc.pdf
my-bucket
= is the bucket name65
= is a folder name65-abc.pdf
= is the file name
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设我在这样的文件夹中有一个 PDF:
我可以使用 传输管理器 - 适用于 Java V2 的 AWS 开发工具包。
您正在使用非常旧的 Java API,它不再被认为是最佳实践。亚马逊强烈建议使用 V2 而不是 V1。
现在这里是 代码 适合此用例。
Assume I have a PDF in a folder like this:
I can easily get this PDF using the Transfer Manager - part of the AWS SDK for Java V2.
YOu are using a very old Java API which is no longer considered best practice. AMazon strongly recommends using V2 over V1.
Now here is the code that works fine for this use case.