Search code examples
androidfileoutputstream

Android- saving string in txt file


I am trying to do very simple thing- save string in a file. But for some reason it saves only first 66 chracters. I tried many diffrent codes but nothing actually works. My current code:

 final String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath();
    File dir = new File(dirPath);
    if(!dir.exists())
        dir.mkdirs();
    File file = new File(dirPath, "file.txt");
    FileOutputStream stream = null;
    try {
        stream = new FileOutputStream(file);

        stream.write(myString);
        stream.flush();
        stream.close();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    } finally {
        try {
            if (stream != null) {
                stream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Solution

  • Try using OutputStreamWriter class to write to file like:

    try
    {
        file.createNewFile();
        FileOutputStream fOut = new FileOutputStream(file);
        OutputStreamWriter outWriter = new OutputStreamWriter(fOut);
        outWriter.append(data);
    
        outWriter.close();
    
        fOut.flush();
        fOut.close();
    }
    catch (IOException e)
    {
        Log.e("Exception", "File write failed: " + e.toString());
    }