无法将文件写入内部存储Android

问题描述

我正在尝试将用户历史记录保存到内部存储中,这似乎可行(没有错误):

        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();

但是当我尝试打开它时,我得到了FileNotFoundException

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

我在做什么错了?

解决方法

根据评论,我设法找到答案,我使用了:

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

具有以下功能:

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,n));
        }
        String json =  new String(fileContent);
        return json;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...