下载 AWS S3 Java SDK 的文件帮助

发布于 2024-11-27 18:16:40 字数 798 浏览 2 评论 0原文

下面的代码仅适用于从 S3 中的存储桶下载文本文件。这不适用于图像。是否有更简单的方法来使用 AWS 开发工具包管理下载/类型?文档中包含的示例并未使其显而易见。

AWSCredentials myCredentials = new BasicAWSCredentials(
       String.valueOf(Constants.act), String.valueOf(Constants.sk)); 
AmazonS3Client s3Client = new AmazonS3Client(myCredentials);        
S3Object object = s3Client.getObject(new GetObjectRequest("bucket", "file"));
    
BufferedReader reader = new BufferedReader(new InputStreamReader(
       object.getObjectContent()));
File file = new File("localFilename");      
Writer writer = new OutputStreamWriter(new FileOutputStream(file));
    
while (true) {          
     String line = reader.readLine();           
     if (line == null)
          break;            
     
     writer.write(line + "\n");
}
    
writer.close();

The code below only works for downloading text files from a bucket in S3. This does not work for an image. Is there an easier way to manage downloads/types using the AWS SDK? The example included in the documentation does not make it apparent.

AWSCredentials myCredentials = new BasicAWSCredentials(
       String.valueOf(Constants.act), String.valueOf(Constants.sk)); 
AmazonS3Client s3Client = new AmazonS3Client(myCredentials);        
S3Object object = s3Client.getObject(new GetObjectRequest("bucket", "file"));
    
BufferedReader reader = new BufferedReader(new InputStreamReader(
       object.getObjectContent()));
File file = new File("localFilename");      
Writer writer = new OutputStreamWriter(new FileOutputStream(file));
    
while (true) {          
     String line = reader.readLine();           
     if (line == null)
          break;            
     
     writer.write(line + "\n");
}
    
writer.close();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

草莓味的萝莉 2024-12-04 18:16:40

尽管 Mauricio 的答案中编写的代码可以工作 - 并且他关于流的观点当然是正确的 - 亚马逊提供了一种更快的方法来将文件保存在其 SDK 中。我不知道2011年是否还没有,但现在可以了。

AmazonS3Client s3Client = new AmazonS3Client(myCredentials);

File localFile = new File("localFilename");

ObjectMetadata object = s3Client.getObject(new GetObjectRequest("bucket", "s3FileName"), localFile);

Though the code written in Mauricio's answer will work - and his point about streams is of course correct - Amazon offers a quicker way to save files in their SDK. I don't know if it wasn't available in 2011 or not, but it is now.

AmazonS3Client s3Client = new AmazonS3Client(myCredentials);

File localFile = new File("localFilename");

ObjectMetadata object = s3Client.getObject(new GetObjectRequest("bucket", "s3FileName"), localFile);
旧情勿念 2024-12-04 18:16:40

您应该使用 InputStreamOutputStream 类,而不是 ReaderWriter 类:

InputStream reader = new BufferedInputStream(
   object.getObjectContent());
File file = new File("localFilename");      
OutputStream writer = new BufferedOutputStream(new FileOutputStream(file));

int read = -1;

while ( ( read = reader.read() ) != -1 ) {
    writer.write(read);
}

writer.flush();
writer.close();
reader.close();

Instead of Reader and Writer classes you should be using InputStream and OutputStream classes:

InputStream reader = new BufferedInputStream(
   object.getObjectContent());
File file = new File("localFilename");      
OutputStream writer = new BufferedOutputStream(new FileOutputStream(file));

int read = -1;

while ( ( read = reader.read() ) != -1 ) {
    writer.write(read);
}

writer.flush();
writer.close();
reader.close();
旧情别恋 2024-12-04 18:16:40

埃亚尔斯的回答让你成功了一半,但还不是很清楚,所以我会澄清一下。

AmazonS3Client s3Client = new AmazonS3Client(myCredentials);

//This is where the downloaded file will be saved
File localFile = new File("localFilename");

//This returns an ObjectMetadata file but you don't have to use this if you don't want 
s3Client.getObject(new GetObjectRequest(bucketName, id.getId()), localFile);

//Now your file will have your image saved 
boolean success = localFile.exists() && localFile.canRead(); 

Eyals answer gets you half way there but its not all that clear so I will clarify.

AmazonS3Client s3Client = new AmazonS3Client(myCredentials);

//This is where the downloaded file will be saved
File localFile = new File("localFilename");

//This returns an ObjectMetadata file but you don't have to use this if you don't want 
s3Client.getObject(new GetObjectRequest(bucketName, id.getId()), localFile);

//Now your file will have your image saved 
boolean success = localFile.exists() && localFile.canRead(); 
掩耳倾听 2024-12-04 18:16:40

还有更简单的方法可以实现这一点。我使用了下面的代码片段。从 http://docs.ceph.com/docs/mimic/ 获取参考radosgw/s3/java/

AmazonS3 s3client = AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials)).withRegion(Regions.US_EAST_1).build();

s3client.getObject(
                new GetObjectRequest("nomad-prop-pics", "Documents/1.pdf"),
                new File("D:\\Eka-Contract-Physicals-Dev\\Contracts-Physicals\\utility-service\\downlods\\1.pdf")
    );

There is even much simpler way to get this. I used below snippet. Got reference from http://docs.ceph.com/docs/mimic/radosgw/s3/java/

AmazonS3 s3client = AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials)).withRegion(Regions.US_EAST_1).build();

s3client.getObject(
                new GetObjectRequest("nomad-prop-pics", "Documents/1.pdf"),
                new File("D:\\Eka-Contract-Physicals-Dev\\Contracts-Physicals\\utility-service\\downlods\\1.pdf")
    );
哆兒滾 2024-12-04 18:16:40

使用java.nio.file.FilesS3Object复制到本地文件。

public File getFile(String fileName) throws Exception {
    if (StringUtils.isEmpty(fileName)) {
        throw new Exception("file name can not be empty");
    }
    S3Object s3Object = amazonS3.getObject("bucketname", fileName);
    if (s3Object == null) {
        throw new Exception("Object not found");
    }
    File file = new File("you file path");
    Files.copy(s3Object.getObjectContent(), file.toPath());
    return file;
}

Use java.nio.file.Files to copy S3Object to local file.

public File getFile(String fileName) throws Exception {
    if (StringUtils.isEmpty(fileName)) {
        throw new Exception("file name can not be empty");
    }
    S3Object s3Object = amazonS3.getObject("bucketname", fileName);
    if (s3Object == null) {
        throw new Exception("Object not found");
    }
    File file = new File("you file path");
    Files.copy(s3Object.getObjectContent(), file.toPath());
    return file;
}
情栀口红 2024-12-04 18:16:40

依赖 AWS S3 存储桶

implementation "commons-logging:commons-logging-api:1.1"
implementation platform('com.amazonaws:aws-java-sdk-bom:1.11.1000')
implementation 'com.amazonaws:aws-android-sdk-core:2.6.0'
implementation 'com.amazonaws:aws-android-sdk-cognito:2.2.0'
implementation 'com.amazonaws:aws-android-sdk-s3:2.6.0'

从 S3 存储桶下载对象并存储在本地存储中。

try {
                //Creating credentials
                AWSCredentials awsCredentials = new BasicAWSCredentials(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY);

                //Creating S3
                AmazonS3Client s3Client = new AmazonS3Client(awsCredentials);

                //Creating file path
                File dir = new File(this.getExternalFilesDir("AWS"),"FolderName");
                if(!dir.exists()){
                    dir.mkdir();
                }

                //Object Key
                String bucketName = "*** Bucket Name ***";
                String objKey = "*** Object Key ***";
                
                //Get File Name from Object key
                String  name = objKey.substring(objKey.lastIndexOf('/') + 1);

                //Storing file S3 object in file path
                InputStream in = s3Client.getObject(new GetObjectRequest(bucketName, objKey)).getObjectContent();
                Files.copy(in,Paths.get(dir.getAbsolutePath()+"/"+name));
                in.close();

            } catch (Exception e) {
                Log.e("TAG", "onCreate: " + e);
            }

从 S3 存储桶获取对象列表

public void getListOfObject()
    {
        ListObjectsV2Result result ;
        AWSCredentials awsCredentials = new BasicAWSCredentials(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY);
        AmazonS3Client s3Client = new AmazonS3Client(awsCredentials);
        result = s3Client.listObjectsV2(AWS_BUCKET);
        for( S3ObjectSummary s3ObjectSummary : result.getObjectSummaries())
        {
            Log.e("TAG", "onCreate: "+s3ObjectSummary.getKey() );
        }
    }

检查是否有对象桶中是否存在

public String isObjectAvailable(String object_key)
    {

        try {
            AWSCredentials awsCredentials = new BasicAWSCredentials(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY);
            AmazonS3 s3 = new AmazonS3Client(awsCredentials);
            String bucketName = AWS_BUCKET;
            S3Object object = s3.getObject(bucketName, object_key);
            Log.e("TAG", "isObjectAvailable: "+object.getKey()+","+object.getBucketName() );
        } catch (AmazonServiceException e) {
            String errorCode = e.getErrorCode();
            if (!errorCode.equals("NoSuchKey")) {
               // throw e;
                Log.e("TAG", "isObjectAvailable: "+e );
            }

            return "no such key";
        }
        return "null";
    }

Dependencies AWS S3 bucket

implementation "commons-logging:commons-logging-api:1.1"
implementation platform('com.amazonaws:aws-java-sdk-bom:1.11.1000')
implementation 'com.amazonaws:aws-android-sdk-core:2.6.0'
implementation 'com.amazonaws:aws-android-sdk-cognito:2.2.0'
implementation 'com.amazonaws:aws-android-sdk-s3:2.6.0'

Download object from S3 bucket and store in local storage.

try {
                //Creating credentials
                AWSCredentials awsCredentials = new BasicAWSCredentials(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY);

                //Creating S3
                AmazonS3Client s3Client = new AmazonS3Client(awsCredentials);

                //Creating file path
                File dir = new File(this.getExternalFilesDir("AWS"),"FolderName");
                if(!dir.exists()){
                    dir.mkdir();
                }

                //Object Key
                String bucketName = "*** Bucket Name ***";
                String objKey = "*** Object Key ***";
                
                //Get File Name from Object key
                String  name = objKey.substring(objKey.lastIndexOf('/') + 1);

                //Storing file S3 object in file path
                InputStream in = s3Client.getObject(new GetObjectRequest(bucketName, objKey)).getObjectContent();
                Files.copy(in,Paths.get(dir.getAbsolutePath()+"/"+name));
                in.close();

            } catch (Exception e) {
                Log.e("TAG", "onCreate: " + e);
            }

Get List of Object from S3 Bucket

public void getListOfObject()
    {
        ListObjectsV2Result result ;
        AWSCredentials awsCredentials = new BasicAWSCredentials(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY);
        AmazonS3Client s3Client = new AmazonS3Client(awsCredentials);
        result = s3Client.listObjectsV2(AWS_BUCKET);
        for( S3ObjectSummary s3ObjectSummary : result.getObjectSummaries())
        {
            Log.e("TAG", "onCreate: "+s3ObjectSummary.getKey() );
        }
    }

Check if any object exists in bucket or not

public String isObjectAvailable(String object_key)
    {

        try {
            AWSCredentials awsCredentials = new BasicAWSCredentials(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY);
            AmazonS3 s3 = new AmazonS3Client(awsCredentials);
            String bucketName = AWS_BUCKET;
            S3Object object = s3.getObject(bucketName, object_key);
            Log.e("TAG", "isObjectAvailable: "+object.getKey()+","+object.getBucketName() );
        } catch (AmazonServiceException e) {
            String errorCode = e.getErrorCode();
            if (!errorCode.equals("NoSuchKey")) {
               // throw e;
                Log.e("TAG", "isObjectAvailable: "+e );
            }

            return "no such key";
        }
        return "null";
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文