java 保存和读取本地json文件
Posted 星朝
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 保存和读取本地json文件相关的知识,希望对你有一定的参考价值。
保存数据到本地文件
- private void saveDataToFile(String fileName,String data) {
- BufferedWriter writer = null;
- File file = new File("d:\"+ fileName + ".json");
- //如果文件不存在,则新建一个
- if(!file.exists()){
- try {
- file.createNewFile();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- //写入
- try {
- writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,false), "UTF-8"));
- writer.write(data);
- } catch (IOException e) {
- e.printStackTrace();
- }finally {
- try {
- if(writer != null){
- writer.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- System.out.println("文件写入成功!");
- }
取数据
- private String getDatafromFile(String fileName) {
-
- String Path="d:\" + fileName+ ".json";
- BufferedReader reader = null;
- String laststr = "";
- try {
- FileInputStream fileInputStream = new FileInputStream(Path);
- InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
- reader = new BufferedReader(inputStreamReader);
- String tempString = null;
- while ((tempString = reader.readLine()) != null) {
- laststr += tempString;
- }
- reader.close();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (reader != null) {
- try {
- reader.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- return laststr;
- }
以上是关于java 保存和读取本地json文件的主要内容,如果未能解决你的问题,请参考以下文章
在一个活动中加载单个片段两次,从本地json文件中加载2个问题