猿问

如何将自定义数据保存到文本文件?

我正在开发一个对我自己的业务有帮助的应用程序(计费应用程序),我需要将数据存储在设备中。我需要特别保存到文本文件,但我不知道我必须做什么。我必须保存的数据类型:


(mydata.txt)

##

id:1

heatUsage:2123

waterUsage:45,4

##

id:2

heatUsage:4572

waterUsage:21,2

##

id:3

heatUsage:456

waterUsage:11,4

##

谁能知道如何以编程方式保存此文件?


红糖糍粑
浏览 121回答 1
1回答

幕布斯7119047

希望这可能对你有用。您可以格式化数据,例如:&nbsp; &nbsp; public String formatData(List<User> users) {&nbsp; &nbsp; &nbsp; &nbsp; StringBuilder stringBuilder = new StringBuilder();&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < users.size(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; stringBuilder.append("##\n");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; stringBuilder.append("id:" + user.getId() + "\n");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; stringBuilder.append("heatUsage:" + user.getHeatUsage() + "\n");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; stringBuilder.append("waterUsage:" + user.getWaterUsage() + "\n");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return stringBuilder.toString();&nbsp; &nbsp; }并写入文件:private void writeToFile(String data,Context context) {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("filename.txt", Context.MODE_PRIVATE));&nbsp; &nbsp; &nbsp; &nbsp; outputStreamWriter.write(data);&nbsp; &nbsp; &nbsp; &nbsp; outputStreamWriter.close();&nbsp; &nbsp; }&nbsp; &nbsp; catch (IOException e) {&nbsp; &nbsp; &nbsp; &nbsp; Log.e("Exception", "File write failed: " + e.toString());&nbsp; &nbsp; }&nbsp;}
随时随地看视频慕课网APP

相关分类

Java
我要回答