Matt Newbill
Matt Newbill

Reputation: 130

Saving Android text file does not write text in the file

the goal of this code is to save a text file called test.txt in the ABCPrint folder.
It is currently creating the folder and creating the test.txt file, but when I open the file there is no text in it. I have tried everything and from what it looks like it is not a permission issue.

Does anyone see anything wrong with the code below that would prevent it from writing the string to the file?

try {

    File testFolder = new File(Environment.getExternalStorageDirectory(),"ABCPrint");
    testFolder.mkdirs();

    File file = new File(testFolder, "test.txt");
    boolean isnew =file.createNewFile();

    FileOutputStream fileOut = openFileOutput(file.getName(), Context.MODE_WORLD_WRITEABLE);
    OutputStreamWriter outputWriter = new OutputStreamWriter(fileOut);

    outputWriter.write("Hello World!");
    outputWriter.write("\n");
    outputWriter.flush();
    outputWriter.close();
    fileOut.flush();
    fileOut.close();

} catch (Exception e) {

    Log.i("Error", "Here", e);
}

Upvotes: 0

Views: 854

Answers (1)

Batuhan Coşkun
Batuhan Coşkun

Reputation: 2969

Everytime you call this lines, your file is being created again. There is another easy way to do this:

File testFolder = new File(
            Environment.getExternalStorageDirectory(),
            "ABCPrint");
if (!testFolder.exists())
{
    try
    {
        testFolder.createNewFile();
    } 
    catch (IOException e){
        e.printStackTrace();
    }
}
try
{
    //BufferedWriter for performance, true to set append to file flag
    BufferedWriter buf = new BufferedWriter(new FileWriter(testFolder, true)); 
    buf.append("Hello World!");
    buf.newLine();
    buf.close();
}
catch (IOException e){
    e.printStackTrace();
}

Good luck.

Upvotes: 3

Related Questions