Skip to content
Advertisement

How to create a Path to a non existent file

How can I create a Path to a file which is guaranteed not to exist?

I thought about using an “impossible” path name, such as:

Path path = Path.of("/nonexistent");

But somebody could create such a file, making my code fail.

Update

I have written a method which accepts a Path and then tries to read from the underlying file, and now I am writing a unit test to make sure I have correctly handled non existing files.

I wish to make my unit test robusts, without risking random failures.

Advertisement

Answer

Create a temporary directory for the test, then any file path under that directory won’t exist – use that for your tests.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement