java AWS 上传 中文文件 设置文件编码
时间: 2024-05-02 16:23:36 浏览: 272
aws-java-sdk-s3-1.12.397.jar中文-英文对照文档.zip
为UTF-8的方法是什么?
您可以使用以下Java代码将文件上传到AWS S3,并设置文件编码为UTF-8:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
public class S3Uploader {
private static final String BUCKET_NAME = "your-bucket-name";
private static final String ACCESS_KEY = "your-access-key";
private static final String SECRET_KEY = "your-secret-key";
public static void main(String[] args) {
BasicAWSCredentials awsCreds = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
.withRegion(Regions.DEFAULT_REGION)
.build();
String filePath = "path/to/your/file.txt";
String keyName = "your-file-name.txt";
File file = new File(filePath);
try (InputStream inputStream = new FileInputStream(file)) {
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentEncoding(StandardCharsets.UTF_8.toString());
objectMetadata.setContentType("text/plain");
objectMetadata.setContentLength(file.length());
PutObjectRequest request = new PutObjectRequest(BUCKET_NAME, keyName, inputStream, objectMetadata);
s3Client.putObject(request);
} catch (AmazonServiceException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在这个例子中,我们使用AWS SDK for Java V2将一个文件上传到AWS S3,设置文件编码为UTF-8,并设置文件的Content-Type为"text/plain"。您可以在ObjectMetadata对象中设置其他自定义元数据。
阅读全文