Create a folder relative to the user project directory from a library

Hi,

I would like to create a folder in the directory the user is running their code from.
Something like this works fine usually:
val path = Paths.get(".\folderName\")
if(!(Files.exists(path) && Files.isDirectory(path)))
Files.createDirectory(path)
and creates a folder “folderName” relative to the project directory.
But if I publish the code as a library and try to do this again it fails to create the directory.
Is there a way to create a folder relative to the user directory from a library?

Using slashes instead of backslashes should work across OSs/file systems.

The current working directory is available as system property “user.dir”, i.e. sys.props.get("user.dir"), but this should already be used for resolving the leading dot. So the question is, what is the current working directory in your invocation scenario and why does it fail to create the directory (exception message,…)?

1 Like

Thanks, changing the backslashes to forward slashes seems to have fixed it :slight_smile:
And sys.props.get(“user.dir”) gives the correct directory.

BTW, the ./ is redundant since folderName is a relative path to the current directory already, so it means the same thing as ./folderName.

Also, you should avoid constructing paths manually using slash or backslashes, use the Paths.get method with multiple arguments:

Paths.get(".", "folderName")

this constructs a valid path for the underlying filesystem, OS agnostic.

Furthemore, your code contains a race condition, since between your check and the call to Files.createDirectory, the world can change and the call might fail. Better just use Files.createDirectories without first checking whether the directory already exists or not.

2 Likes