Home > Enterprise >  File Not Found when reading a file created during runtime as resource
File Not Found when reading a file created during runtime as resource

Time:03-24

This line returns null because it can't find the file:

inputStream = getClass().getClassLoader().getResourceAsStream(filename);

The file is src/test/resources/test.tmp.

The file is written to like this:

Files.write(Paths.get(file.getAbsolutePath()), "test".getBytes(StandardCharsets.UTF_8));

If I create file before running the application then it works but if I create file during runtime then inputStream returns as null because file is not found.

How do I create a file during runtime that can be read from the resources directory as a Stream?

CodePudding user response:

The getResourceAsStream system fundamentally doesn't "do" writes. That method will retrieve a resource from wherever the system is loaded classes from, and there is no guarantee that 'whereever' that might be supports the notion of writing. In fact, all available places it could be coming from do not support it.. except running from 'raw' class files. Which is a situation that generally only holds during development, thus, making this a pointless exercise.

Hence, the code you wrote does not work and cannot be made to work. If you want to write data, getResourceAsStream cannot be involved in the process.

More generally, code is in locations that you can't write to. Or, should be - a few backwater OSes have crazy bad security defaults and allow you to do so. This simply means said OS sucks, not that you should run right off the cliff after them. Hence, any hackery (which is certainly available, but fragile, as it requires certain classpath setups that java doesn't guarantee) should be avoided - all you'll end up obtaining is a directory that you can't write to. Or shouldn't be writing to.

The correct place to store data is.. not 'next to / inside the jar'. It's in the user's home dir, the 'Documents' dir, or some location configured by the user.

You can get to a user's home dir with Paths.get(System.getProperty("user.home")).

  •  Tags:  
  • java
  • Related