Is it possible to gzip and upload this string to Amazon S3 without ever being written to disk?

前端 未结 2 995
北荒
北荒 2021-02-06 00:38

I know this is probably possible using Streams, but I wasn\'t sure the correct syntax.

I would like to pass a string to the Save method and have it gzip the string and u

2条回答
  •  一向
    一向 (楼主)
    2021-02-06 01:18

    This is essentially what aperkins suggested. I don't know the interface to AS3, so his suggestion to create a ByteArrayInputStream over the byte array is probably the way to go.

    import java.io.*;
    import java.util.zip.GZIPOutputStream;
    
    import com.amazonaws.auth.PropertiesCredentials;
    import com.amazonaws.services.s3.AmazonS3;
    import com.amazonaws.services.s3.AmazonS3Client;
    import com.amazonaws.services.s3.model.PutObjectRequest;
    
    public class FileStore {
        public static void Save(String data) throws IOException {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
            Writer writer = new OutputStreamWriter(baos);
            writer.write(data);
            writer.flush();
            writer.close();
    
            byte[] zippedBytes = gzipFile(baos.toByteArray());
    
            AmazonS3 s3 = new AmazonS3Client(new PropertiesCredentials(
                new FileInputStream("AwsCredentials.properties")));
    
            String bucketName = "mybucket";
            String key = "test/" + zippedFile.getName();
    
            s3.putObject(new PutObjectRequest(bucketName, key,
                new ByteArrayInputStream(zippedBytes));
        }
    
        public static byte[] gzipFile(byte[] bytes) throws IOException {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                GZIPOutputStream out = new GZIPOutputStream(baos);
                out.write(bytes, 0, bytes.length);
                // Complete the GZIP file
                out.finish();
                out.close();
    
                return baos.toByteArray();
            } catch (IOException e) {
                throw e;
            }
        }
    }
    

提交回复
热议问题