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

huangapple go评论72阅读模式
英文:

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

我做错了什么?

英文:

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 ?

答案1

得分: 0

根据评论,我成功找到了答案,我使用了:

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

使用以下函数:

public String fileToString(String fileName) {
    try {
        FileInputStream fis = new FileInputStream (fileName);  // 第2行
        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;
    }
}
英文:

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

huangapple
  • 本文由 发表于 2020年8月15日 20:55:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/63426280.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定