Search code examples
javaandroidfileinputstream

Can't write file to internal storage Android


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 ?


Solution

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