在其中一个api中,使用Apache ioutil使用以下步骤将S3Object
转换为String
:
S3ObjectInputStream inputStream = s3Object.getObjectContent();
String streamString = IOUtils.toString(inputStream);
在其他API中,当我必须将字符串转换回S3ObjectInputStream
时,我尝试以下步骤,但它似乎不起作用:
方法1:
String streamString = IOUtils.toString(inputStream); // --> from the 1st API
S3ObjectInputStream s3ObjectInputStream = new S3ObjectInputStream
(new ByteArrayInputStream(streamString.getBytes()), null); --> Returning an incorrect/null inputstream
方法2:
String streamString = IOUtils.toString(inputStream); // --> from the 1st API
InputStream sampleStream = IOUtils.toInputStream(streamString, StandardCharsets.UTF_8);
是否有其他方法来正确转换它而不丢失数据?
我试过了,它工作正常。您的问题可能在其他地方(可能是您的inputStream
)。
这是工作代码(包括您的代码)
@Test
public void testS3ObjectInputStream() throws IOException {
String originalString = "Hello World";
InputStream inputStream =
new ByteArrayInputStream(originalString.getBytes(StandardCharsets.UTF_8));
// your code
String streamString = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
S3ObjectInputStream s3ObjectInputStream =
new S3ObjectInputStream(
new ByteArrayInputStream(streamString.getBytes(StandardCharsets.UTF_8)), null);
assertNotNull(s3ObjectInputStream); //PASSES!
String recoveredString = IOUtils.toString(s3ObjectInputStream, StandardCharsets.UTF_8);
assertEquals(originalString, recoveredString); //PASSES!
}