Skip to content

Commit

Permalink
Delete the FileBackedOutputStream temp file if writing to it fails.
Browse files Browse the repository at this point in the history
We don't delete the temp file when the stream is closed, because that would be a change in observable behaviour.

Fixes #1664.

RELNOTES=If writing to the temp file in `FileBackedOutputStream` fails, we now delete it before propagating the exception.
PiperOrigin-RevId: 369433020
  • Loading branch information
eamonnmcmanus authored and Google Java Core Libraries committed Apr 20, 2021
1 parent 9acb9a0 commit 6e054ce
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 10 deletions.
15 changes: 10 additions & 5 deletions android/guava/src/com/google/common/io/FileBackedOutputStream.java
Original file line number Diff line number Diff line change
Expand Up @@ -225,12 +225,17 @@ private void update(int len) throws IOException {
// this is insurance.
temp.deleteOnExit();
}
FileOutputStream transfer = new FileOutputStream(temp);
transfer.write(memory.getBuffer(), 0, memory.getCount());
transfer.flush();
try {
FileOutputStream transfer = new FileOutputStream(temp);
transfer.write(memory.getBuffer(), 0, memory.getCount());
transfer.flush();
// We've successfully transferred the data; switch to writing to file
out = transfer;
} catch (IOException e) {
temp.delete();
throw e;
}

// We've successfully transferred the data; switch to writing to file
out = transfer;
file = temp;
memory = null;
}
Expand Down
15 changes: 10 additions & 5 deletions guava/src/com/google/common/io/FileBackedOutputStream.java
Original file line number Diff line number Diff line change
Expand Up @@ -224,12 +224,17 @@ private void update(int len) throws IOException {
// this is insurance.
temp.deleteOnExit();
}
FileOutputStream transfer = new FileOutputStream(temp);
transfer.write(memory.getBuffer(), 0, memory.getCount());
transfer.flush();
try {
FileOutputStream transfer = new FileOutputStream(temp);
transfer.write(memory.getBuffer(), 0, memory.getCount());
transfer.flush();
// We've successfully transferred the data; switch to writing to file
out = transfer;
} catch (IOException e) {
temp.delete();
throw e;
}

// We've successfully transferred the data; switch to writing to file
out = transfer;
file = temp;
memory = null;
}
Expand Down

0 comments on commit 6e054ce

Please sign in to comment.