title: How to set default file permissions for Java
body: <p><strong>Question</strong>: I'm looking for a way to configure Java to create new files with a particular permission set by default. </p>
  
  <p><strong>Problem</strong>: I have a Spring Boot app which uses the following:</p>
  
  <ul>
  <li>Log4J2 for logging</li>
  <li>H2 for flat file databases</li>
  <li>Ehcache for cached entities</li>
  </ul>
  
  <p>All of these libraries create new files on the local file system, and when they do, they produce world-writeable files (666 for files and 777 for directories). I have seen this on macOS 10.13 (user has "umask 0022") and on Amazon Linux (user has "umask 0002").</p>
  
  <p>If I was directly managing the creation of the files, I can do what I need with <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/PosixFilePermission.html" rel="nofollow noreferrer">PosixFilePermission</a>, but since file creation is delegated to the libraries, I don't have that opportunity. I could potentially set a timer to discover new files and set the permissions directly, but I'm not wild about that approach. </p>
  
  <p>Log4J2 v2.9 added a filePermissions field to <a href="https://logging.apache.org/log4j/2.x/manual/appenders.html#RollingFileAppender" rel="nofollow noreferrer">RollingFileAppender</a>, so I have hope for one of my problems, but I'm not able to find something similar for H2 or Ehcache. Ideally, I'd like to do this at the JVM/Boot level for simplicity and future-proofing.</p>