从/向文件java写入/读取字节数组

时间:2022-09-19 09:13:13

I have a java serializable object and I want to write/read that object to/from a file. Yet Google app engine does not support fileoutputstream and objectoutputstream so I convert the serializable object to a byte array and write it to file

我有一个java可序列化的对象,我想在文件中写入/读取该对象。然而谷歌应用程序引擎不支持fileoutputstream和objectoutputstream所以我将可序列化对象转换为字节数组并将其写入文件

$FileWriteChannel writeChannel = fileService.openWriteChannel(
writableFile, lockForWrite);
$writeChannel.write(ByteBuffer.wrap(bytearray));
$writeChannel.closeFinally();

Then I read the file:

然后我读了这个文件:

AppEngineFile readableFile = new AppEngineFile(filename);
FileReadChannel readChannel = fileService.openReadChannel(readableFile, lockForRead);
BufferedReader reader = new BufferedReader(Channels.newReader(readChannel, "UTF-8"));
String line = reader.toString();

I see the log and I got error with UTF-8 Can anybody show me what I did incorrectly ?
Error log:

我看到日志,我得到了UTF-8的错误任何人都可以告诉我我做错了什么?错误日志:

cloud.spam.filter.server.SerializationObject file_io: An error message: invalid stream header: 5B4240312012/07/06 08:00:10

Thank you

1 个解决方案

#1


0  

Consider using protobuf for this purpose. Beside the fact that it's more compact format than standard java serialization, it will also give you ability to change (by adding new fields) class to be written into file.

考虑使用protobuf用于此目的。除了它比标准java序列化更紧凑的格式之外,它还使您能够更改(通过添加新字段)类以写入文件。

#1


0  

Consider using protobuf for this purpose. Beside the fact that it's more compact format than standard java serialization, it will also give you ability to change (by adding new fields) class to be written into file.

考虑使用protobuf用于此目的。除了它比标准java序列化更紧凑的格式之外,它还使您能够更改(通过添加新字段)类以写入文件。