我是buidling和android游戏,每当他或其他人玩游戏时,它应该在游戏中存储用户的名字和分数。 所以我需要将数据保存在json文件中,因为后者我想要读取文件并在屏幕上显示它们。 当文件被创建并且我想在其上添加附加json内容时,它就会起作用。
public void writeToJsonfile(String name, int scoreForBasketGame)
throws
JSONException, IOException {
String jsonFile = Environment.getExternalStorageDirectory()
+ "/" + "usersScoreOnBasketGame.txt";
File file = new File(jsonFile);
if (!file.exists()) {
JSONArray jsonArray = new JSONArray();
JSONObject tempObj = new JSONObject();
tempObj.put("Name", name);
tempObj.put("scoreForBasketGame", scoreForBasketGame);
jsonArray.put(tempObj);
try (FileWriter newfile = new FileWriter(jsonFile)) {
newfile.write(jsonArray.toString());
}
}
else {
FileReader fileReader = new FileReader(jsonFile);
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(fileReader);
String line;
while ((line = br.readLine()) != null) {
text.append(line);
}
br.close();
} catch (IOException e) {
Log.d("File error", "Cant read the file");
}
JSONArray jsonArray = new JSONArray(text.toString());
JSONObject objToAdd = new JSONObject();
objToAdd.put("Name", name);
objToAdd.put("scoreForBasketGame", scoreForBasketGame);
jsonArray.put(objToAdd);
FileWriter filewriter = new FileWriter(jsonFile);
filewriter.write(String.valueOf(jsonArray));
}
}
答案 0 :(得分:-1)
我做的事情非常类似于保存.txt文件信息而不能与远程数据库同步,我强烈建议使用gson(查找gson依赖并在项目中实现)将对象解析为json和保存它。
public void userToFile(List<User> data){
JsonArray jsonArray = new JsonArray();
Gson gson = new Gson();
for (User user : data) {
jsonArray.add(gson.toJson(user));
}
Log.i("JSON",jsonArray.toString());
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"name of your file" + ".txt");
Log.i("PATH_FILE",Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
try {
Writer output = new BufferedWriter(new FileWriter(file));
output.write(jsonArray.toString());
output.close();
Toast.makeText(this, "File generated", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
如果您只想保存一个用户,请将JsonArray改为JsonObject并使用相同的逻辑。这将文本文件保存在外部下载文件夹中,并且不要忘记在清单中实现此任务的权限。
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>