援引:Doc ID 109095.1
首先,在数据库端创建调用Unix shell的java类,用Runtime.getRuntime().exec()实现
1.
CREATE OR REPLACE JAVA SOURCE NAMED "CaptureStream" as
import java.util.*;
import java.io.*;
class CaptureStream implements Runnable {
private final InputStream is;
private final String type;
private final OutputStream redirect;
private boolean redirected = false;
CaptureStream(InputStream is, String type, OutputStream redirect)
{
this.is = is;
this.type = type + ">";
this.redirect = redirect;
}
CaptureStream(InputStream is, String type)
{
this(is, type, null);
}
CaptureStream(InputStream is)
{
this(is, " ", null);
}
public void run()
{
try {
PrintWriter pw = null;
if (redirect != null) {
pw = new PrintWriter(redirect);
redirected = true;
}
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null) {
System.out.println(type + line);
if (redirected) {
pw.println(line);
}
}
if (redirected) {
pw.flush();
pw.close();
}
br.close();
isr.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
};
/
2.
CREATE OR REPLACE JAVA SOURCE NAMED "ExecOSCmd" as
import java.util.*;
import java.io.*;
public class ExecOSCmd {
public static void main (String args[])
{
int rc = 0;
if (args.length < 1) {
System.out.println("USAGE: java ExecOSCmd \'cmd\' ");
System.exit(1);
}
try {
String cmd = args[0];
FileOutputStream fos = null;
if (args.length == 2 ) {
fos = new FileOutputStream(args[1]);
}
Runtime rt = Runtime.getRuntime();
Process p = rt.exec(cmd);
CaptureStream err = new CaptureStream(p.getErrorStream(), "ERR");
Thread e = new Thread(err);
/* NOTE we do not join the error thread. If there was no
Error it may never return. We would wait forever for it to
return thus janging this process */
e.start();
CaptureStream out = new CaptureStream(p.getInputStream(),
"OUT", fos);
Thread o = new Thread(out);
o.start();
try {
rc = p.waitFor();
/* Handle exceptions for waitFor() */
} catch (InterruptedException intexc) {
System.out.println("Interrupted Exception on waitFor: " +
intexc.getMessage());
}
if (fos !=null) {
o.join(); // need to wait for the output to finish.
fos.flush();
fos.close();
}
System.out.println("ExitValue: " + rc);
} catch (Throwable t) {
System.out.println("ExitValue: " + rc);
t.printStackTrace();
}
}
};
/
3.定义调用2的存储过程
CREATE OR REPLACE PROCEDURE executecmd
AS
language java name 'ExecOSCmd.main(java.lang.String[])';
4.在数据库Command Window调用步骤3
首先,设置将输出项显示
SQL> set serveroutput on
SQL> call dbms_java.set_output(5000);
Method called
SQL> exec executecmd('ls -ls');
OUT>total 895254