Skip to content

Instantly share code, notes, and snippets.

@ndw
Created September 5, 2021 08:47
Show Gist options
  • Save ndw/b2a8f5c6a3a8880ac72765b5672c8290 to your computer and use it in GitHub Desktop.
Save ndw/b2a8f5c6a3a8880ac72765b5672c8290 to your computer and use it in GitHub Desktop.
Java program to demonstrate that NIO will delete files that are read-only
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.util.HashSet;
import java.util.Set;
public class NioTest {
public static void main(String[] argv) throws Exception {
System.out.println("Hello, world");
Path foo = Paths.get("foo");
if (Files.exists(foo)) {
System.out.println("Foo exists: " + Files.exists(foo));
} else {
// Make the test file
new FileOutputStream("foo").close();
Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.GROUP_READ);
perms.add(PosixFilePermission.OTHERS_READ);
Files.setPosixFilePermissions(foo, perms);
}
// Buh bye
Files.delete(foo);
}
}
@reinhapa
Copy link

reinhapa commented Sep 5, 2021

What JDK do you use?

@ndw
Copy link
Author

ndw commented Sep 5, 2021

I get the same results for both

$ java -version
java version "1.8.0_231"
Java(TM) SE Runtime Environment (build 1.8.0_231-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.231-b11, mixed mode)

and

$ /Library/Java/JavaVirtualMachines/jdk-11.0.10.jdk/Contents/Home/bin/java -version
java version "11.0.10" 2021-01-19 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.10+8-LTS-162)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.10+8-LTS-162, mixed mode)

@dizzzz
Copy link

dizzzz commented Sep 5, 2021

Something for foo.toFile().delete()

@dizzzz
Copy link

dizzzz commented Sep 5, 2021

The file gets the right permissions... hmmm

-r--r--r-- 1 wessels staff 0 Sep 5 19:21 foo

@dizzzz
Copy link

dizzzz commented Sep 5, 2021

Could it be that..... Deleting is OK because the permissions of the containing directory allows deletion ? The file can't be updated as expected...

@reinhapa
Copy link

reinhapa commented Sep 6, 2021

Linux (POSIX) checks the directory settings for delete/create/write files

@ndw
Copy link
Author

ndw commented Sep 6, 2021

Indeed. To be fair, I wasn't making any assertion that there was a bug. I just commented that the behavior surprised me. I don't think it should have! :-)

@reinhapa
Copy link

reinhapa commented Sep 6, 2021

A day when I learn something, is a good day 😊

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment