I am trying to run a perl command with Java runtime exec in linux/ubuntu/gnome. The command generates an pdf file, but it saves it in my home folder. 开发者_如何学编程Is there any way that the exec method can set an output path for the commands executed? Thanks in advance.
The exec
method just runs the command on the operating system, so you'll want to change the command you're running with exec
more than anything in "Java" per se.
There are a few possibilities:
Change the working directory of your java program. The
.pdf
is being saved in your working directory because this is where the program is being run.Unfortunately it's not simple to change this value after the program has been launched. It is, however, trivial to change before the program starts; just change the working directory before starting the program.
Move the file to it's desired location after it's been created in your home directory.
Change the command so that it includes the target location. Your perl script may have an option that will enable you to save it's output to a certain location (usually
-o
or--output
). Using this your program would change from:Runtime.exec("perl someprogram");
to something like:
Runtime.exec("perl someprogram -o /path/to/some.file")
You might be able to use "output redirection", if there is no option to do this.
Try something like what's below as your argument:
Runtime.exec("perl someprogram > /path/to/some.file")
Unfortunately, without knowing more details of your situation I can't provide more concrete advice.
While each approach has benefits and drawbacks, it's probably best to just implement the one that you understand best; if you can't get one to work, try another.
A good, free online resource for learning is Introduction to Linux: A Hands On Guide.
Section 2.2 has details on cd
which you can use for 1.
.
Section 3.3, section 3 teaches about the mv
command, which will be useful in 2.
.
Section 5.1 is about I/O redirection. Knowing about "output redirection" and the >
operator, are important for 4.
.
For 3.
, you'll have to consult the documentation of the perl program you're using.
You could modify the Perl script to accept an absolute path for the output.
You can trying setting the working directory using exec(java.lang.String[], java.lang.String[], java.io.File)
where File is the directory the command is executed from.
If all else fails, you'll can always copy the generated file from the Home directory to your final location.
精彩评论