-- Oracle存储过程获取操作系统目录下文件列表 -- 1). 创建临时表 eygle@SZTYORA> create global temporary table dirlist( filename varchar2(255), filesize number, filedate date) on commit delete rows; / -- 创建临时表保存文件列表信息。此处使用临时表的好处是:循环取文件列表时无需对表进行清空处理。 -- 2). 创建JAVA SOURCE过程 -- 此过程用户访问操作系统目录并读取文件列表. eygle@SZTYORA> create or replace and compile java source named DirList as import java.io.*; import java.sql.*; public class DirList { public static void getList(String directory) throws SQLException { File path=new File(directory); String[] fileList=path.list(); String fileName; long fileSize; long fileDate; for (int i=0;i<fileList.length; i++) { fileName=fileList[i]; File fpath=new File(directory+'/'+fileName); fileSize=fpath.length(); fileDate=fpath.lastModified(); #sql{insert into dirlist(filename, filesize, filedate) values(:fileName,:fileSize,to_date('01/01/1970','mm/dd/yyyy')+:fileDate/(24*60*60*1000))}; } } } / -- 3). 创建ORACLE存储过程 -- 此过程用于调用和执行JAVA存储过程(DirList) eygle@SZTYORA> create or replace procedure get_dir_list( p_directory in varchar2 ) as language java name 'DirList.getList( java.lang.String )'; / -- 4). 执行p_get_dir_list过程获取数据 eygle@SZTYORA> exec get_dir_list('/u01/app/oracle/admin/sztyora/bdump');
会出现以下错误:ERROR at line 1:
ORA-29532: Java call terminated by uncaught Java exception: java.security.AccessControlException: the Permission
(java.io.FilePermission /u01/app/oracle/admin/sztyora/bdump read) has not been granted to EYGLE. The PL/SQL to grant this is
dbms_java.grant_permission( 'EYGLE', 'SYS:java.io.FilePermission', '/u01/app/oracle/admin/sztyora/bdump', 'read' )
ORA-06512: at "EYGLE.GET_DIR_LIST", line 1
ORA-06512: at line 1
-- 执行时出错,提示无权限。这里耽误了很久,搜索了很多关于这个错误的帖子,都未提到解决办法。 -- 后来根据这个错误提示,用SYS执行: sys@SZTYORA> exec dbms_java.grant_permission( 'EYGLE', 'SYS:java.io.FilePermission', '/u01/app/oracle/admin/sztyora/bdump', 'read' ); PL/SQL procedure successfully completed sys> exec dbms_java.grant_permission( 'EYGLE', 'SYS:java.io.FilePermission', '/u01/app/oracle/admin/sztyora/bdump/*', 'read' ); PL/SQL procedure successfully completed -- 此处需要用SYS用户执行dbms_java.grant_permission分别授权目录和目录文件列表(*代替即可)访问权限给指定用户。 -- 然后执行: eygle@SZTYORA> exec get_dir_list('/u01/app/oracle/admin/sztyora/bdump'); PL/SQL procedure successfully completed5.查询文件列表信息
eygle@SZTYORA> col FILESIZE for 999999999999 eygle@SZTYORA> col FILENAME for a40 eygle@SZTYORA> col FILEDATE for a30 eygle@SZTYORA> select * from dirlist; eygle@SZTYORA> select * from dirlist;
注意:#sql{insert into dirlist(filename, filesize, filedate)
values(:fileName,:fileSize,to_date('01/01/1970','mm/dd/yyyy')+:fileDate/(24*60*60*1000))};
这里用了SQLJ语法。不用数据库连接,没有进行测试!