无法将文件写入内部存储器 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());
具有以下功能:
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;
}
}
我正在尝试将用户历史记录保存到内部存储器,这似乎有效(没有错误):
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, 0, n));
}
String json = new String(fileContent);
return json;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}