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

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

Can't write file to internal storage Android

问题

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

  1. Gson gson = new Gson();
  2. String json = gson.toJson(userHistory);
  3. historyFile = new File(context.getFilesDir() + File.separator + "MyApp" + File.separator + "UserHistory.json");
  4. FileOutputStream fileOutputStream = new FileOutputStream(historyFile);
  5. fileOutputStream.write(json.getBytes());
  6. fileOutputStream.flush();
  7. fileOutputStream.close();

但是,当我尝试打开它时,我得到了一个“FileNotFoundException”:

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

我做错了什么?

英文:

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

  1. Gson gson = new Gson();
  2. String json = gson.toJson(userHistory);
  3. historyFile = new File(context.getFilesDir() + File.separator + "MyApp" + File.separator + "UserHistory.json");
  4. FileOutputStream fileOutputStream = new FileOutputStream(historyFile);
  5. fileOutputStream.write(json.getBytes());
  6. fileOutputStream.flush();
  7. fileOutputStream.close();

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

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

What am I doing wrong ?

答案1

得分: 0

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

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

使用以下函数:

  1. public String fileToString(String fileName) {
  2. try {
  3. FileInputStream fis = new FileInputStream (fileName); // 第2行
  4. StringBuffer fileContent = new StringBuffer("");
  5. byte[] buffer = new byte[1024];
  6. int n;
  7. while ((n = fis.read(buffer)) != -1)
  8. {
  9. fileContent.append(new String(buffer, 0, n));
  10. }
  11. String json = new String(fileContent);
  12. return json;
  13. } catch (IOException e) {
  14. e.printStackTrace();
  15. return null;
  16. }
  17. }
英文:

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

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

With the function below :

  1. public String fileToString(String fileName) {
  2. try {
  3. FileInputStream fis = new FileInputStream (fileName); // 2nd line
  4. StringBuffer fileContent = new StringBuffer("");
  5. byte[] buffer = new byte[1024];
  6. int n;
  7. while ((n = fis.read(buffer)) != -1)
  8. {
  9. fileContent.append(new String(buffer, 0, n));
  10. }
  11. String json = new String(fileContent);
  12. return json;
  13. } catch (IOException e) {
  14. e.printStackTrace();
  15. return null;
  16. }
  17. }

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:

确定