简体   繁体   中英

Can't write file to internal storage Android

I am trying to save a user history to the internal storage, which seems to work (no error):

        Gson gson = new Gson();
        String json = gson.toJson(userHistory);
        historyFile = new File(context.getFilesDir() + File.separator + "MyApp" + File.separator + "UserHistory.json");
        FileOutputStream fileOutputStream = new FileOutputStream(historyFile);
        fileOutputStream.write(json.getBytes());
        fileOutputStream.flush();
        fileOutputStream.close();

But when I try to open it I got a FileNotFoundException :

        InputStream inputStream = assets.open(historyFile.getAbsolutePath());

What am I doing wrong?

Based on the comment, I managed to find an answer, I use:

String userHistoryJson = fileToString(historyFile.getAbsolutePath());

With the function below:

public String fileToString(String fileName) {
    try {
        FileInputStream fis = new FileInputStream (fileName);  // 2nd line
        StringBuffer fileContent = new StringBuffer("");
        byte[] buffer = new byte[1024];
        int n;
        while ((n = fis.read(buffer)) != -1)
        {
            fileContent.append(new String(buffer, 0, n));
        }
        String json =  new String(fileContent);
        return json;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM