I want to write a program in Java which compiles and runs it, so that the file "output.txt", produced by given Java class, is outputted to a specified folder. How can this be done?
Let's get this straight:
- The existing Java application
A
outputs a file output.txt
... somewhere. You can't change that application.
- You want to write a application
B
that runs A
in such a way that you can control the directory to which output.txt
is written.
Q: Can it be done?
A: It depends on how A
opens the output file.
If A
uses a relative pathname for the file; e.g. new FileWriter(new File("output.txt"))
then it can be done; see below.
If A
uses an absolute pathname for the file; e.g. new FileWriter(new File("/output.txt"))
then it cannot be done. There's no practical way to cause A
to put the file somewhere else. (I wouldn't go so far as to say that it is theoretically impossible, but you'd need to resort to things that no sane developer would seriously contemplate doing.)
How you deal with the relative case is to have B
use the ProcessBuilder
to specify a different current directory for A
when launching it. The javadoc has an example that covers this; look for the use of setDirectory
in the example ... and its specification.
(Note: you can also do this by running an external script that changes directory and runs the command. But that approach involves platform specific things, and should be avoided if you want your code to be portable.)