I have a problem trying to run an sh script from Java. I've already tried with the solutions to similar problems at stack overflow .
The problem is not the call of the script itself, but the command pg_dump :
=> If I run the following script from console ./my_script.sh
everything goes ok:
NOW="$(date +%Y%m%d_%H%M%S)"
BACKUP_FILE="backup_${NOW}.sql"
FOLDER="./backups"
if [ ! -d "$FOLDER" ]; then
mkdir $FOLDER
fi
OUTPUT=${FOLDER}/${BACKUP_FILE}
HOST="my.host.dir"
PORT="8080"
DB_NAME="dbName"
USER="user"
PASS="pass"
OPT="-h ${HOST} -p ${PORT} -U ${USER} -f ${OUTPUT} -c -C -i -b -v ${DB_NAME}"
EXPORT="export PGPASSWORD=${PASS}"
RUN="pg_dump ${OPT}"
echo ${EXPORT}
echo ${RUN}
$EXPORT
$RUN
=> But if I want to call it from Java code, the echo
command success (so the script has been called) but not the pg_dump
command:
int exitValue = 0;
try {
ProcessBuilder pb = new ProcessBuilder(scriptPath);
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
LOG.log(Level.FINE, line);
}
exitValue = p.waitFor();
LOG.log(Level.FINE, "Process exitValue: " + exitValue);
} catch (IOException | InterruptedException e) {
LOG.log(Level.SEVERE, "Executing " + scriptPath, e);
return false;
}
return exitValue == 0;
My question is why the same script from console success but not calling it from Java?
You can try this
try {
ProcessBuilder pb = new ProcessBuilder("script.sh");
Process p = pb.start();
p.waitFor();
System.out.println("Script executed Finish");
}
catch (Exception e)
{
e.printStackTrace();
}
我猜pg_dump在输入/输出流中做了一些相对复杂的事情,所以您可能已经遇到了http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---中列出的一些pitfal 。 won-t.html本文中包含代码清单,在这种情况下可能会有所帮助。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.