安卓:如何将JSON数据保存到文件中并检索它?

10

我对android不熟悉,请帮助我。我正在尝试将我的ToDoList保存到一个文件中,以便下次打开时重新加载所有项目。

这是我目前的代码:

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
gson = new Gson();
    try {
        BufferedReader br = new BufferedReader(new FileReader("storage.json"));
        Entry e = gson.fromJson(br, Entry.class);
        Log.d("reading", e.toString());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }}

@Override
protected void onStop() {
    super.onStop();
    json = gson.toJson(mEntries);
    Log.d("jsondata", json);
    try {
        file1 = new FileWriter("storage.json");
        file1.write(json);
        file1.flush();
        file1.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

Entry.java

public class Entry {
String S;
boolean b;

public Entry(String S, boolean b) {
    this.S = S;
    this.b = b;
}

public String getS() {
    return S;
}

public void setS(String S) {
    this.S = S;
}

public void setB(boolean b) {
    this.b = b;
}

public boolean isB() {
    return b;
}

我该怎么继续?在 onCreate() 方法中,我想要检查文件是否存在,如果存在,则导入文件数据并在屏幕上显示。


可能是如何在Android中从文件中读取/写入字符串的重复问题。 - Madhukar Hebbar
阅读 这里 - Madhukar Hebbar
1个回答

18

每个安卓应用都有自己的内部存储空间,只有该应用可以访问,您可以从中读取或写入。

在您的情况下,您首先需要检查是否存在这样的文件,然后再创建一个。

  private String read(Context context, String fileName) {
    try {
        FileInputStream fis = context.openFileInput(fileName);
        InputStreamReader isr = new InputStreamReader(fis);
        BufferedReader bufferedReader = new BufferedReader(isr);
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    } catch (FileNotFoundException fileNotFound) {
        return null;
    } catch (IOException ioException) {
        return null;
    }
}

private boolean create(Context context, String fileName, String jsonString){
    String FILENAME = "storage.json";
    try {
        FileOutputStream fos = context.openFileOutput(fileName,Context.MODE_PRIVATE);
        if (jsonString != null) {
            fos.write(jsonString.getBytes());
        }
        fos.close();
        return true;
    } catch (FileNotFoundException fileNotFound) {
        return false;
    } catch (IOException ioException) {
        return false;
    }

}

public boolean isFilePresent(Context context, String fileName) {
    String path = context.getFilesDir().getAbsolutePath() + "/" + fileName;
    File file = new File(path);
    return file.exists();
}

在Activity的onCreate方法中,你可以执行以下操作:

boolean isFilePresent = isFilePresent(getActivity(), "storage.json");
if(isFilePresent) {
   String jsonString = read(getActivity(), "storage.json");
   //do the json parsing here and do the rest of functionality of app
} else {
   boolean isFileCreated = create(getActivity, "storage.json", "{}");
   if(isFileCreated) {
     //proceed with storing the first todo  or show ui
   } else {
     //show error or try again.
   }
}

参考 https://developer.android.com/guide/topics/data/data-storage.html#filesInternal


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接