0

I am executing a bunch of SQL scripts and trying to read the output log file, looking for errors, after each file is executed.

Here's how I execute the script.

String strCommand = "sqlcmd -S SERVERNAME -d DBNAME -U USERNAME -P PASSWORD -r0 -i \"SCRIPT.sql\" 2> \"OUTPUT.LOG\" 1> NULL";
Process process = Runtime.getRuntime().exec(strCommand);
process.waitFor();

I've redirected the standard output to NULL and errors to the log file. Immediately following the execution of the above statements, I try to read the contents of the OUTPUT.LOG file, using File Reader and BufferedReader. An exception is thrown when trying to open the OUTPUT.LOG file.

(The system cannot find the file specified)

I check the path where the file should be saved, and needless to say, it isn't there. When I try to manually execute the command via Command Prompt, it works and writes the log file with errors, as expected. What am I doing wrong?

1 Answer 1

2

Your redirections (the 2> etc) will work if you are running from a command shell, but not if you run directly from java like this.

Try the following (for Windows):

String strCommand = "cmd /c sqlcmd -S SERVERNAME -d DBNAME -U USERNAME -P PASSWORD -r0 -i \"SCRIPT.sql\" 2> \"OUTPUT.LOG\" 1> NULL";
Process process = Runtime.getRuntime().exec(strCommand);
process.waitFor();

Note the addition of cmd /c, which will run the string in a command shell.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This worked. I believe using cmd executes the command in the shell and then exits, which finishes writing the file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.