Thursday, October 1, 2009
Java stored procedures in PL/SQL. Reading files.
This post is to demonstrate how to create Java stored procedure in oracle and how to
read files from certain directory on DB server. PL/SQL is restricted to read files only
from the directories specified in DBA_DIRECTORIES table or in utl_file_dir database
parameter. Java store proc on the contrary has the ability to read file from any readable
location.
Step 1. Create Java source and compile.
create or replace and compile java source named ReadFileJava as
import java.sql.*;
import java.io.*;
import oracle.jdbc.*;
import oracle.sql.*;
public class readFileJava
{
public static String returnFile(String fileName) throws IOException{
File file = new File(fileName);
FileReader fis = null;
BufferedReader bis = null;
String fileString="";
String out="";
try {
fis = new FileReader(file);
// Here BufferedInputStream is added for fast reading.
bis = new BufferedReader(fis);
// dis.available() returns 0 if the file does not have more lines.
while ((out = bis.readLine())!=null) {
fileString+=out+"\n";
}
}
catch (IOException ioe) { System.out.println("No file");}
bis.close();
fis.close();
return fileString;
}
}
Step 2.Associate Java source with PL/SQL function.
CREATE OR REPLACE FUNCTION readfileJava(fileName VARCHAR2) RETURN
VARCHAR2
AS
LANGUAGE JAVA NAME 'readFileJava.returnFile(java.lang.String) return
java.lang.String';
Step 3. Use it.
----------------------<
declare
b CLOB;
begin
select ReadFileJava('/usr/tmp/l0347291.tmp') into b from dual;
dbms_output.put_line(length(b));
dbms_output.put_line(substr(b,1,200));
End;