I expected any file can't be deleted while their stream is being used.
but with this code the following job is executed and it works fine.
- open file input stream
- delete the file
- wait for 10 seconds
- write a file with the input stream
Could anyone please teach me why my code works? How could the stream still have the information? will this still okay even if the file is Super large? like, twice a memory?
public static void main(String[] args) throws IOException {
final String HOME = System.getProperty("user.home");
final String ORIGINAL = HOME + "/Downloads/test.jpeg";
final String TARGET = HOME + "/Downloads/targetFile.jpeg";
File file = new File(ORIGINAL);
try (InputStream inputStream = Files.newInputStream(file.toPath())
) {
if (file.delete()) {
log.info("Original file deleted");
} else {
log.info("Failed deleting the original file");
}
for (int i = 0; i < 10; i++) {
log.info("waits {}/10s", i + 1);
Thread.sleep(1000);
}
File targetFile = new File(TARGET);
Files.copy(inputStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
if (targetFile.isFile()) {
log.info("target file created");
if (targetFile.renameTo(file)) {
log.info("target file renamed");
} else {
log.info("target file rename failed");
}
} else {
log.info("{} is not a file", targetFile);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
It still works perfectly. I tested it on Linux and MacOS as well, but still both are OK. Could anyone please give me some hint to understand this situation? I got so confused.