ObjectInputStream对象输入流

ObjectInputStream对象输入流

  • 读取(反序列化)的顺序需要和你保存数据(序列化)的顺序一致
public class ObjectInputStream01 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        String filePath = "D:\\data.dat";
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));

        System.out.println(ois.readInt());
        System.out.println(ois.readBoolean());
        System.out.println(ois.readChar());
        System.out.println(ois.readDouble());
        System.out.println(ois.readUTF());
        Object dog = ois.readObject();
        System.out.println("运行类型:"+dog.getClass());
        System.out.println("dog信息:"+dog);

        ois.close();
    }
}

 

可以使用Java中的ByteArrayOutputStream来将S3ObjectInputStream转换为InputStream。具体步骤如下: 1. 创建一个ByteArrayOutputStream实例,用于存储S3ObjectInputStream中的数据。 2. 创建一个byte数组缓冲区,大小为1024或更大。 3. 从S3ObjectInputStream中读取数据,并将其写入ByteArrayOutputStream中。 4. 关闭S3ObjectInputStream。 5. 从ByteArrayOutputStream中获取字节数组,然后使用ByteArrayInputStream将其封装为InputStream。 下面是示例代码: ```java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import com.amazonaws.services.s3.model.S3ObjectInputStream; public class S3ObjectInputStreamToInputStreamConverter { public static InputStream convert(S3ObjectInputStream s3is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = s3is.read(buffer)) != -1) { baos.write(buffer, 0, len); } s3is.close(); byte[] bytes = baos.toByteArray(); return new ByteArrayInputStream(bytes); } } ``` 可以使用以下代码调用该转换器: ```java import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectInputStream; public class ExampleUsage { public static void main(String[] args) throws IOException { AmazonS3 s3Client = AmazonS3ClientBuilder.defaultClient(); S3Object s3Object = s3Client.getObject("my-bucket-name", "my-object-key"); S3ObjectInputStream s3is = s3Object.getObjectContent(); InputStream is = S3ObjectInputStreamToInputStreamConverter.convert(s3is); // 使用is进行其他操作 } } ``` 在以上示例中,从S3中获取对象并打开S3ObjectInputStream。然后,使用S3ObjectInputStreamToInputStreamConverter.convert方法将其转换为标准的InputStream,以供其他操作使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值