更新Amazon S3存储桶中的文件 [英] Updating a file in Amazon S3 bucket

查看:80
本文介绍了更新Amazon S3存储桶中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将一个字符串附加到存储在S3中的文本文件的末尾.目前,我只是将文件的内容读入字符串,追加新文本并将文件重新保存回S3.有一个更好的方法吗.我认为文件是>>> 10MB时,然后读取整个文件不是一个好主意,因此我应该如何正确执行此操作?

I am trying to append a string to the end of a text file stored in S3. Currently I just read the contents of the file into a String, append my new text and resave the file back to S3. Is there a better way to do this. I am thinkinig when the file is >>> 10MB then reading the entire file would not be a good idea so how should I do this correctly?

当前代码[代码]

private void saveNoteToFile( String p_note ) throws IOException, ServletException    
{
    String str_infoFileName =  "myfile.json"; 

    String existingNotes = s3Helper.getfileContentFromS3( str_infoFileName  ); 
    existingNotes += p_note;
    writeStringToS3( str_infoFileName , existingNotes );        
}

public void writeStringToS3(String p_fileName, String p_data) throws IOException 
{
  ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( p_data.getBytes());

  try {
      streamFileToS3bucket(  p_fileName, byteArrayInputStream, p_data.getBytes().length);
  } 
  catch (AmazonServiceException e)
  {
      e.printStackTrace();
  } catch (AmazonClientException e)
  {
      e.printStackTrace();
  }
}

public void streamFileToS3bucket( String p_fileName,  InputStream input, long size)
{
    //Create sub folders if there is any in the file name.
    p_fileName = p_fileName.replace("\\", "/");
    if( p_fileName.charAt(0) == '/')
    {
        p_fileName = p_fileName.substring(1, p_fileName.length());
    }
    String folder = getFolderName( p_fileName );
    if( folder.length() > 0)
    {
        if( !doesFolderExist(folder))
        {
            createFolder( folder );
        }
    }
    ObjectMetadata metadata =  new ObjectMetadata();
    metadata.setContentLength(size);
    AccessControlList acl = new AccessControlList();
    acl.grantPermission(GroupGrantee.AllUsers, Permission.Read);

    s3Client.putObject(new PutObjectRequest(bucket, p_fileName , input,metadata).withAccessControlList(acl));
}

[/code]

推荐答案

无法将其追加到AWS S3上的现有文件.当您上传对象时,它会创建一个新版本(如果已经存在):

It's not possible to append to an existing file on AWS S3. When you upload an object it creates a new version if it already exists:

如果您上传的对象的键名已经存在于存储桶,Amazon S3将创建该对象的另一个版本,而不是替换现有对象

If you upload an object with a key name that already exists in the bucket, Amazon S3 creates another version of the object instead of replacing the existing object

来源: http://docs.aws.amazon.com/AmazonS3/latest/UG/ObjectOperations.html

对象是不可变的.

在这些AWS论坛线程中也提到过:

It's also mentioned in these AWS Forum threads:

https://forums.aws.amazon.com/message.jspa?messageID = 179375 https://forums.aws.amazon.com/message.jspa?messageID=540395

这篇关于更新Amazon S3存储桶中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆