Reputation: 81
I have a code snippet that will open a local file by input/output stream, but it will sleep or wait for a moment (at this time, the stream still open, not close), while I delete that file by another file management progam. The behavior seem difference between Java and Android.
Java: That file cannot be deleted because another program is accessing it - FileInputStream still not close
File f = new File("D:\\" + File.separator + "testfile.txt");
try {
f.createNewFile();
FileInputStream fis = new FileInputStream(f);
// Still not close
try {
Thread.sleep(60000); // At this time I will use another program to delete this file
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
Android: That file can be deleted normally - although FileInputStream still not close
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "testfile.txt");
try {
f.createNewFile();
FileInputStream fis = new FileInputStream(f);
// Still not close
try {
Thread.sleep(60000); // At this time I will use another program to delete this file
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
Can anyone explain to me why has the diffence between these platform? I just know android reuse java sdk, may be their behavior have been modified while migrating from java to android? Or another reason....?
Upvotes: 0
Views: 69
Reputation: 719279
Can anyone explain to me why has the diffence between these platform
It is actually a difference between Linux (and Android, and Mac OSX)1 versus Windows.
Linux, etc implement file deletion by "unlinking" the file, and only actually deleting it when all file handles have been closed.
In Windows (at least historically), deleting a file deleted it there and then, and therefore deleting a file that was open was implementable. That has changed, but the restrictions on deleting remain. (See the "DeleteFile function" page from MSDN.)
1 - The designs of the Linux, Android and Mac OSX operating systems are all derived from classic UNIX, and UNIX has used "unlink" semantics for file removal since at least as far back as Version 6. Windows derives ultimately from MS/DOS.
Upvotes: 2
Reputation: 357
As m0skit0 pointed out, this is not a Java vs. Java@Android difference. If you would try your Android example on Linux, you would get the same result.
Java relies on the underlying operating system's behavior when it comes to file operations and this is where Windows (your first example) and Linux differ (at least with their corresponding default/standard filesystems).
Upvotes: 0