繁体   English   中英

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

[英]Can't write file to internal storage 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());

使用下面的 function:

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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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