英文:
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;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论