1

I have a java application that reads and writes csv files. I have created a read only directory on my Mac that my application will try to write a csv file to. I did this with chmod 000. No file gets created but no error is thrown either. Furthermore, checking that the file was created with Files.notExists() returns False. My application needs to detect that no csv was created to inform the user. What is going on here?

public void writeCSV(String fileName, List<String> results) throws IOException {
    // fileName = "~/no_write/results.csv"

    try(CSVPrinter printer = new CSVPrinter(Files.newBufferedWriter(Paths.get(fileName)), CSVFormat.DEFAULT.withHeader(header)) {
        for (String result : results) {
            printer.printRecord(result);
        }
    }

    if (Files.notExists(Paths.get(fileName))) { // returns False but no_write directory is empty
        throw new IOException();
    }

    if (!Files.exists(Paths.get(fileName))) { // Files.exists returns True
        throw new IOException();
    }
}
iansumm
  • 31
  • 4

1 Answers1

1

As mentioned in the comments, the solution is to get the absolute path. When the absolute path is used the directory permissions are picked up and an IOException is generated. No need to check whether the file exists anymore.

public void writeCSV(String fileName, List<String> results) throws IOException {
    // fileName = "~/no_write/results.csv"

    try(CSVPrinter printer = new CSVPrinter(Files.newBufferedWriter(Paths.get(fileName).toAbsolutePath()), CSVFormat.DEFAULT.withHeader(header)) {
        for (String result : results) {
            printer.printRecord(result);
        }
    }
}
iansumm
  • 31
  • 4