1

I would expect exception to be thrown in this code at line: charSink.write("hi world"); since the file is set to be non writable. But this code executes without any exceptions. How to make CharSink respect file permissions?


public class CharSinkWritingNonWritableFile {
    public static void main(String[] args) throws Exception {

        final File file = getNewFile();

        file.setWritable(false, false);

        val charSink = Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND);

        file.setWritable(false, false);
        
        charSink.write("hi world");

        Files.readLines(file, Charsets.UTF_8).forEach(line -> {
            System.out.println(line);
        });

    }

    private static File getNewFile() {

        final File file = new File("/tmp/hi-world");
        if (file.exists()) {
            file.delete();
        }
        return file;
    }
}

Edit:

OS: MacOS 12.4

user7858768
  • 838
  • 7
  • 22
  • which os are you using, windows ? setExecutable alse false and check this answer please. https://stackoverflow.com/a/14415997/2165146 – muhammed ozbilici Aug 22 '22 at 20:15
  • What's the value returned from `file.setWritable(false, false);`? [That will return `false` if the call fails](https://docs.oracle.com/javase/7/docs/api/java/io/File.html#setWritable(boolean,%20boolean)). – Andrew Henle Aug 22 '22 at 20:35
  • Additionally, metadata doesn't always sync instantly, so it might be possible to finish a write before the changes are prevented. – Colin Alworth Sep 06 '22 at 17:25

0 Answers0