java开发AmazonS3对象存储的工具类

上两节说了文档上默认不用证书的方式操作对象,但大部分时候出于安全考虑是要用到证书认证的。下面就是对这种情况下的对象操作。
1.引入pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>com.zhanglfgroupId>
    <artifactId>AmazonS3artifactId>
    <version>0.0.1-SNAPSHOTversion>
    <packaging>jarpackaging>

    <name>AmazonS3name>
    <url>http://maven.apache.orgurl>

    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>

    
    
    
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.amazonawsgroupId>
                <artifactId>aws-java-sdk-bomartifactId>
                <version>1.11.125version>
                <type>pomtype>
                <scope>importscope>
            dependency>
        dependencies>
    dependencyManagement>
    
    <dependencies>
        <dependency>
            <groupId>com.amazonawsgroupId>
            <artifactId>aws-java-sdk-s3artifactId>
        dependency>
        <dependency>
            <groupId>com.amazonawsgroupId>
            <artifactId>aws-java-sdk-dynamodbartifactId>
        dependency>
    dependencies>
project>

2.查询存储对象的工具类,有三种方法

package com.zhanglf.aws;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ListObjectsV2Request;
import com.amazonaws.services.s3.model.ListObjectsV2Result;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectSummary;

public class AWSListTest extends AwsConfig {
    public void listObject(){
        AWSCredentials credentials=new BasicAWSCredentials(accessKey,secretKey);
        ClientConfiguration clientConfig=new ClientConfiguration();

        try {
            clientConfig.setProtocol(Protocol.HTTP);
            AmazonS3Client conn=new AmazonS3Client(credentials,clientConfig);
            conn.setEndpoint(ENDPOINT);

            ObjectListing objects = conn.listObjects(bucketName);
            do {
                for(S3ObjectSummary objectSummary:objects.getObjectSummaries()){
                    System.out.println(objectSummary.getKey());
                }
            } while (objects.isTruncated());
        } catch (AmazonServiceException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (AmazonClientException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void listObjectWithClientBuilder(){
        AWSCredentials credentials=new BasicAWSCredentials(accessKey,secretKey);
        ClientConfiguration clientConfig=new ClientConfiguration();
        try {
            clientConfig.setProtocol(Protocol.HTTP);
            AmazonS3ClientBuilder builder=AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentials));
            EndpointConfiguration endpointConfiguration=new EndpointConfiguration(ENDPOINT,Regions.AP_NORTHEAST_1.getName());
            builder.setEndpointConfiguration(endpointConfiguration);

            AmazonS3 conn=builder.build();

            ListObjectsV2Request req=new ListObjectsV2Request().withBucketName(bucketName);

            ListObjectsV2Result result;
            do{
                result= conn.listObjectsV2(req);
                for(S3ObjectSummary objectSummary :result.getObjectSummaries()){

                    System.out.println(objectSummary.getKey());
                }
            }while(result.isTruncated());

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void getObjectByKey(String key){
        AWSCredentials credentials=new BasicAWSCredentials(accessKey,secretKey);
        ClientConfiguration clientConfig=new ClientConfiguration();
        try {
            clientConfig.setProtocol(Protocol.HTTP);
            AmazonS3ClientBuilder builder=AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentials));
            EndpointConfiguration endpointConfiguration=new EndpointConfiguration(ENDPOINT,Regions.AP_NORTHEAST_1.getName());
            builder.setEndpointConfiguration(endpointConfiguration);

            AmazonS3 conn=builder.build();

            S3Object object = conn.getObject(bucketName, key);
            System.out.println(object.getKey());

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

3.将对象上传到AWS的工具类,也有三种方法

package com.zhanglf.aws;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;

public class AWSUploadTest extends AwsConfig {
    private File file = new File("D:/root/zlf/20171108/yuanzougaofei.mp3");

    /**
     * 
     * @param key 指定的上傳目録
     * @throws FileNotFoundException
     */
    public void uploadObject(String key) throws FileNotFoundException {
        AWSCredentials credentials = new BasicAWSCredentials(accessKey,
                secretKey);
        ClientConfiguration clientConfig = new ClientConfiguration();
        clientConfig.setProtocol(Protocol.HTTP);
        AmazonS3Client conn = new AmazonS3Client(credentials, clientConfig);
        conn.setEndpoint(ENDPOINT);

        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(file.length());
        metadata.addUserMetadata("managecom", "1");
        metadata.addUserMetadata("name", "zhanglf");
        metadata.addUserMetadata("pro", "hn");

        FileInputStream fi = new FileInputStream(file);

        conn.putObject(bucketName, key, fi, metadata);

        GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucketName, key);
        URL url = conn.generatePresignedUrl(urlRequest);
        System.out.println(url.toString());

    }


    public void uploadObjectWithClientBuilder(String key) throws FileNotFoundException{
        AWSCredentials credentials=new BasicAWSCredentials(accessKey,secretKey);
        ClientConfiguration clientConfig=new ClientConfiguration();
            clientConfig.setProtocol(Protocol.HTTP);
            AmazonS3ClientBuilder builder=AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentials));
            EndpointConfiguration endpointConfiguration=new EndpointConfiguration(ENDPOINT,Regions.AP_NORTHEAST_1.getName());
            builder.setEndpointConfiguration(endpointConfiguration);

            AmazonS3 conn=builder.build();

            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(file.length());
            metadata.addUserMetadata("managecom", "1");
            metadata.addUserMetadata("name", "zhanglf");
            metadata.addUserMetadata("pro", "hn");

            FileInputStream fi = new FileInputStream(file);

            conn.putObject(bucketName, key, fi, metadata);

            GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucketName, key);
            URL url = conn.generatePresignedUrl(urlRequest);
            System.out.println(url.toString());
    }


    public void uploadToS3(String key){
        AmazonS3 s3=new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey));
        Region usWest2=Region.getRegion(Regions.US_WEST_2);
        s3.setRegion(usWest2);
        s3.setEndpoint(ENDPOINT);

        s3.putObject(new PutObjectRequest(bucketName, key, file));
        S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));

        GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucketName, key);
        Date expirationDate =null;
        try {
            expirationDate=new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-23");
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        urlRequest.setExpiration(expirationDate);
        //生成url
        URL url = s3.generatePresignedUrl(urlRequest);
        System.out.println(url.toString());
    }
}
public void deleteObjectWithClientBuilder(String key){
        AWSCredentials credentials=new BasicAWSCredentials(accessKey,secretKey);
        ClientConfiguration clientConfig=new ClientConfiguration();
            clientConfig.setProtocol(Protocol.HTTP);
            AmazonS3ClientBuilder builder=AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentials));
            EndpointConfiguration endpointConfiguration=new EndpointConfiguration(ENDPOINT,Regions.AP_NORTHEAST_1.getName());
            builder.setEndpointConfiguration(endpointConfiguration);

            AmazonS3 conn=builder.build();
            conn.deleteObject(bucketName, key);
    }

你可能感兴趣的:(文件操作)