Use the streams provide by the Process returned by the exec.
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Process.html
Process p = Runtime.getRuntime().exec("sqlplus user/pwd@connect @test.sql");
OutputStream os = p.getOutputStream();
This code launches sql*plus and runs the script in the 'filename' variable. It displays the results in NetBeans console.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.File;
import java.util.Map;
public class test1 {
public static void main (String args []) {
test_script();
}
public static void test_script () {
String fileName = "@test_table.sql";
String sqlPath = "E:\\";
String sqlCmd = "sqlplus";
String arg1 = "user/password@sid"; -- plug in your user, password and db name
String arg2 = fileName;
try {
String line;
ProcessBuilder pb = new ProcessBuilder(sqlCmd, arg1, arg2);
Map<String, String> env = pb.environment();
env.put("VAR1", arg1);
env.put("VAR2", arg2);
pb.directory(new File(sqlPath));
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader bri = new BufferedReader
(new InputStreamReader(p.getInputStream()));
BufferedReader bre = new BufferedReader
(new InputStreamReader(p.getErrorStream()));
while ((line = bri.readLine()) != null) {
System.out.println(line);
}
bri.close();
while ((line = bre.readLine()) != null) {
System.out.println(line);
}
bre.close();
System.out.println("Done.");
}
catch (Exception err) {
err.printStackTrace();
}
}
}
Here is the contents of the script placed at E:
test_table.sql
Prompt drop TABLE ANOTHER_TEST;
DROP TABLE ANOTHER_TEST CASCADE CONSTRAINTS
/
Prompt Table ANOTHER_TEST;
CREATE TABLE ANOTHER_TEST
(
BATCH_SEQ NUMBER,
BATCH_GROUP_ID NUMBER,
STATUS_FLAG VARCHAR2(30 BYTE),
OBJ_BEING_PROCESSED VARCHAR2(80 BYTE),
BATCH_RUN_START_DTTM DATE,
BATCH_RUN_END_DTTM DATE,
CREATE_DTTM DATE,
CREATE_USER VARCHAR2(30 BYTE),
UPDATE_DTTM DATE,
UPDATE_USER VARCHAR2(30 BYTE)
)
LOGGING
NOCOMPRESS
NOCACHE
PARALLEL ( DEGREE DEFAULT INSTANCES DEFAULT )
MONITORING
/
COMMENT ON TABLE ANOTHER_TEST IS 'This is a test table.'
/
EXIT
/