Skip to content

Instantly share code, notes, and snippets.

@TWiStErRob
Created August 31, 2014 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TWiStErRob/45c8e9937c5483191ba5 to your computer and use it in GitHub Desktop.
Save TWiStErRob/45c8e9937c5483191ba5 to your computer and use it in GitHub Desktop.
Check if Java environment hangs on to File descriptors when using FileOutputStream
public static boolean isFOSHoldingOnToFile() {
return !canDeleteCreatedFile() || !canRenameCreatedFile();
}
public static boolean canDeleteCreatedFile() {
File temp = null;
try {
temp = File.createTempFile("canDeleteCreatedFile", null, Robolectric.application.getCacheDir());
if(!temp.delete()) {
return false;
}
assertFalse(temp.exists());
writeFile(temp, "content".getBytes());
return temp.delete();
} catch(Exception ex) {
return false; // if anything above goes wrong we can assume it won't work
} finally {
if (temp != null) {
temp.delete();
temp.deleteOnExit();
}
}
}
public static boolean canRenameCreatedFile() {
File temp1 = null;
File temp2 = null;
try {
temp1 = File.createTempFile("canRenameCreatedFile", null, Robolectric.application.getCacheDir());
temp2 = File.createTempFile("canRenameCreatedFile", null, Robolectric.application.getCacheDir());
if(!temp1.delete() || !temp2.delete()) {
return false;
}
assertFalse(temp1.exists());
assertFalse(temp2.exists());
writeFile(temp1, "content".getBytes());
return temp1.renameTo(temp2);
} catch(Exception ex) {
return false; // if anything above goes wrong we can assume it won't work
} finally {
if (temp1 != null) {
temp1.delete();
temp1.deleteOnExit();
}
if (temp2 != null) {
temp2.delete();
temp2.deleteOnExit();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment