在Amazon S3文件上传过程中,使用FileInputStream和InputStream都可以实现文件上传。以下是使用这两种方法的代码示例:
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.PutObjectRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class S3FileUploadExample {
public static void main(String[] args) throws IOException {
String bucketName = "your-bucket-name";
String key = "your-object-key";
String filePath = "path/to/your/file.jpg";
AmazonS3 s3Client = new AmazonS3Client();
try {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
s3Client.putObject(new PutObjectRequest(bucketName, key, fis, null));
} catch (AmazonServiceException e) {
// Handle Amazon S3 service exception
e.printStackTrace();
} catch (IOException e) {
// Handle file IO exception
e.printStackTrace();
}
}
}
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.PutObjectRequest;
import java.io.InputStream;
public class S3FileUploadExample {
public static void main(String[] args) {
String bucketName = "your-bucket-name";
String key = "your-object-key";
InputStream inputStream = null;
AmazonS3 s3Client = new AmazonS3Client();
try {
// Get the input stream of your file from any source
inputStream = getInputStream();
s3Client.putObject(new PutObjectRequest(bucketName, key, inputStream, null));
} catch (AmazonServiceException e) {
// Handle Amazon S3 service exception
e.printStackTrace();
} finally {
// Close the input stream
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static InputStream getInputStream() {
// Implement this method to return the input stream of your file
// It could be a FileInputStream, ByteArrayInputStream, etc.
return null;
}
}
无论使用FileInputStream还是InputStream,都需要确保文件的输入流被正确关闭以避免资源泄漏。