Context: My software depends on calling a library which can only accept relative paths as an input because of an old limitation. I need the paths to be relative to a known directory. The library might make a call internally like
java.io.File fooBar = new java.io.File("foo/bar");
I need this to give me /nwd/foo/bar
and not, say, /cwd/foo/bar
where /cwd
is the working directory from which java
was run.
For all intents and purposes, I cannot modify the internal behavior of this library. Manually overriding the methods which instantiate these objects would involve basically rewriting the entire library.
A tempting solution would be to just System.setProperty("user.dir", "/nwd")
before calling the library, but this doesn't actually give me the desired effect. Indeed, if I called fooBar.getAbsolutePath()
, I would get the desired /nwd/foo/bar
, but if I checked fooBar.exists()
or tried to open the file for reading or writing, it would appear that the file doesn't exist, because it's actually trying to open /cwd/foo/bar
. In fact, if fooBar
were instead initialized by
java.io.File fooBar = new java.io.File(new java.io.File("foo/bar").getAbsolutePath());
that would actually work, because then the File
object actually contains absolute references.
At this point, I'm so frustrated that I don't care if this requires a hacky solution. I just need the effect of changing the working directory.