packagecom.inslink.sinosoft.util;importjava.io.File;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.util.List;importcom.amazonaws.AmazonServiceException;importcom.amazonaws.ClientConfiguration;importcom.amazonaws.Protocol;importcom.amazonaws.auth.AWSStaticCredentialsProvider;importcom.amazonaws.auth.BasicAWSCredentials;importcom.amazonaws.client.builder.AwsClientBuilder;importcom.amazonaws.services.s3.AmazonS3;importcom.amazonaws.services.s3.AmazonS3ClientBuilder;importcom.amazonaws.services.s3.model.Bucket;importcom.amazonaws.services.s3.model.ObjectListing;importcom.amazonaws.services.s3.model.S3Object;importcom.amazonaws.services.s3.model.S3ObjectInputStream;importcom.amazonaws.services.s3.model.S3ObjectSummary;public classS3Sample {public static void main(String[] args) throwsIOException {//创建Amazon S3对象使用明确凭证
BasicAWSCredentials credentials = new BasicAWSCredentials("your accesskey", "your secretkey");
ClientConfiguration clientConfig= newClientConfiguration();
clientConfig.setSignerOverride("S3SignerType");//凭证验证方式
clientConfig.setProtocol(Protocol.HTTP);//访问协议
AmazonS3 s3Client =AmazonS3ClientBuilder.standard()
.withCredentials(newAWSStaticCredentialsProvider(credentials))
.withClientConfiguration(clientConfig)
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(//设置要用于请求的端点配置(服务端点和签名区域)
"s3.yiducloud.cn","cn-north-1")).withPathStyleAccessEnabled(true)//是否使用路径方式,是的话s3.yiducloud.cn/bucketname
.build();
System.out.println("Uploading a new object to S3 from a file\n");//枚举bucket
List buckets =s3Client.listBuckets();for(Bucket bucket : buckets) {
System.out.println("Bucket: " +bucket.getName());
}//枚举bucket下对象
ObjectListing objects = s3Client.listObjects("sinosoft-ocr-bucket");do{for(S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
System.out.println("Object: " +objectSummary.getKey());
}
objects=s3Client.listNextBatchOfObjects(objects);
}while(objects.isTruncated());//文件上传
try{
s3Client.putObject("bucketname", "keyname", new File("your file path"));
}catch(AmazonServiceException e) {
System.err.println(e.getErrorMessage());
System.exit(1);
}//文件下载
try{
S3Object o= s3Client.getObject("bucketname", "your file‘s keyname");
S3ObjectInputStream s3is=o.getObjectContent();
FileOutputStream fos= new FileOutputStream(new File("your save file path"));byte[] read_buf = new byte[1024];int read_len = 0;while ((read_len = s3is.read(read_buf)) > 0) {
fos.write(read_buf,0, read_len);
}
s3is.close();
fos.close();
}catch(AmazonServiceException e) {
System.err.println(e.getErrorMessage());
System.exit(1);
}catch(FileNotFoundException e) {
System.err.println(e.getMessage());
System.exit(1);
}catch(IOException e) {
System.err.println(e.getMessage());
System.exit(1);
}//其他操作方法参考:https://docs.aws.amazon.com/zh_cn/sdk-for-java/v1/developer-guide/examples-s3-objects.html
//或者下载官网源码
}
}