英文:
How can I serialize/deserialize a Proto object to a local storage in Android project?
问题
如何将Proto数据保存到文件中?
如果我的Proto数据看起来像这样,我能把它保存到文件中吗?还是我需要在Proto文件中做一些更改?
message GameHistory {
repeated Game game = 1;
}
message Game {
string title = 1;
oneof entity {
Easy easy = 2;
Hard hard = 3;
}
}
message Easy {
}
message Hard {
bool isPaid = 1;
int32 number_of_levels = 2;
}
以下是我在Java代码中的游戏列表:
GameResponse.Game game1 = GameResponse.Game.newBuilder().setTitle("Asd").setEasy(GameResponse.Easy.getDefaultInstance()).build();
GameResponse.Game game2 = GameResponse.Game.newBuilder().setTitle("Bsd").setHard(GameResponse.Hard.getDefaultInstance()).build();
final GameResponse.GameHistory build = GameResponse.GameHistory.newBuilder().addGame(game1).addGame(game2).build();
英文:
How can I save Proto data in a file?
If my proto data looks like this, can I save this in a file or do I need to make some changes in my Proto file?
message GameHistory {
repeated Game game = 1;
}
message Game {
string title = 1;
oneof entity {
Easy easy = 2;
Hard hard = 3;
}
}
message Easy {
}
message Hard {
Bool isPaid =1;
int32 number_of_levels = 2;
}
Here is my list of games in Java code:
GameResponse.Game game1 = GameResponse.Game.newBuilder().setTitle("Asd").setEasy(GameResponse.Easy.getDefaultInstance()).build();
GameResponse.Game game2 = GameResponse.Game.newBuilder().setTitle("Bsd").setHard(GameResponse.Hard.getDefaultInstance()).build();
final GameResponse.GameHistory build = GameResponse.GameHistory.newBuilder().addGame(game1).addGame(game2).build();
答案1
得分: 1
使用com.google.protobuf
,GameResponse.GameHistory
类包含以下两种方法:
void writeTo(final OutputStream output)
static GameResponse.GameHistory parseFrom(InputStream input)
因此,您可以使用这两种方法来将协议消息写入/从文件中读取。
// 写入:
File file = new File(context.getExternalFilesDir(null), "fileName.bin");
OutputStream fos = FileOutputStream(file);
gameHistory.writeTo(fos);
fos.flush();
fos.close();
// 读取:
File file = new File(context.getExternalFilesDir(null), "fileName.bin");
InputStream fis = FileInputStream(file);
GameResponse.GameHistory gameHistory = GameResponse.GameHistory.parseFrom(fis);
fis.close();
英文:
Using com.google.protobuf
the GameResponse.GameHistory
class contains both methods of:
void writeTo(final OutputStream output)
static GameResponse.GameHistory parseFrom(InputStream input)
So, you will be able to use these two methods in order to write/read a protocol message to/from a file.
// to write:
File file = new File(context.getExternalFilesDir(null), "fileName.bin");
OutputStream fos = FileOutputStream(file);
gameHistory.writeTo(fos);
fos.flush();
fos.close();
// to read:
File file = new File(context.getExternalFilesDir(null), "fileName.bin");
InputStream fis = FileInputStream(file);
GameResponse.GameHistory gameHistory = GameResponse.GameHistory.parseFrom(fis);
fis.close();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论