3

I'm using this code

for (Uri fileUri : files) {
  File destFile = ...
  InputStream is = getContentResolver().openInputStream(fileUri);

  FileUtils.copyInputStreamToFile(is, destFile);
}

And if user remove the battery of the phone after this for cycle then the some files (lasts) are corrupted.

Is it possible to prevent this?

I tried copy the InputStream to the temp directory and then use

 FileUtils.moveFile(temp, destFile);

for each file but there was the same problem.

Can I somehow close the copied files? Make sure they are copied successfully?

Pepa Zapletal
  • 2,879
  • 3
  • 39
  • 69
  • 1
    Is `FileUtils` a class you wrote? In method `copyInputStreamToFile()`, are `flush` and `sync` used? As an example, see method `copyToFile()` at line 190 of [this file](https://android.googlesource.com/platform/frameworks/base/+/cd92588/core/java/android/os/FileUtils.java). – Bob Snyder Nov 19 '15 at 03:35
  • No. FileUtils are from Apache Commons IO. Thanks for your info. I will try the copyToFile() that you suggested. – Pepa Zapletal Nov 19 '15 at 04:05
  • Some more info is here: http://stackoverflow.com/questions/4072878/i-o-concept-flush-vs-sync – Pepa Zapletal Nov 19 '15 at 04:43

1 Answers1

2

I solved this issue by using this:

FileOutputStream out = new FileOutputStream(filename);

[...]

out.flush();
out.getFD().sync();

from I/O concept flush vs sync

Look at the https://android.googlesource.com/platform/frameworks/base/+/cd92588/core/java/android/os/FileUtils.java and method copyToFile(InputStream inputStream, File destFile) It's nice example how to sole this.

Thanks to qbix!

Community
  • 1
  • 1
Pepa Zapletal
  • 2,879
  • 3
  • 39
  • 69