0

I have a strange issue, when replacing a file by another. This code works well the first time :

String fileContent = "test";    

File file = new File(Environment.getExternalStorageDirectory() + "/myApp/text.txt");
    file.getParentFile().mkdirs();
    if (file.exists())
        file.delete();

    try {
        FileOutputStream fileOutputStream = new FileOutputStream(filePath);
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

        bufferedOutputStream.write(fileContent.getBytes());

        bufferedOutputStream.close();
        fileOutputStream.close();

    } catch (Exception exception) {
        exception.printStackTrace();
    }

It creates a file with this content :

test

Then I execute the code again, replacing the "test" string by a longer string :

String fileContent = "admiral";

It removes the old file, create a new one, BUT it only write the 4 first characters :

admi

Finally, if I replace the content by a shorter string ("be", it creates a corrupted file :

be\00\00

But if I remove the file manually, it works... Very strange...

SOLVED : The problem was, gedit's cache! :s, by the way thx all for your help ! :)

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Greelings
  • 4,964
  • 7
  • 34
  • 70

3 Answers3

0

Try to overwrite the content using this :

FileOutputStream fileOutputStream = new FileOutputStream(filePath, false);
diegoveloper
  • 93,875
  • 20
  • 236
  • 194
0

I don't understand why you need to use BufferedOutputStream... Just try to write using FileOutputStream in this way:

String fileContent = "test";    
File file = new File(Environment.getExternalStorageDirectory() + "/myApp/text.txt");
    file.getParentFile().mkdirs();
    if (file.exists())
        file.delete();

    try {
        FileOutputStream fileOutputStream = new FileOutputStream(filePath);

        fileOutputStream.write(fileContent.getBytes());

        fileOutputStream.close();

    } catch (Exception exception) {
        exception.printStackTrace();
    }

Reference: this question

dalla92
  • 432
  • 2
  • 8
0

First be aware that String.getBytes() without the optional parameter for the charset, takes that of the current platform.

For appending one would need to call:

FileOutputStream fileOutputStream = new FileOutputStream(filePath, true);

In your case you want to replace the contents, and your construct does that already. Remove delete as that gives better system behavior.

Then the final problem writing only 4 bytes.

   bufferedOutputStream.write(fileContent.getBytes());

As if the old file length (of "test" = 4 bytes) was used to write the new content. I cannot explain that, so maybe the removal of delete might cause the bug to disappear.

What might be the case, is that the file is opened elsewhere.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138