利用utl_file读写文件

利用utl包来读写文件需要先设置文件目录

已sys用户登录

CREATE DIRECTORY recv_area AS 'd:test' ;

CREATE DIRECTORY send_area AS 'd:test' ;

这样就创建了目录,下面将对此目录的读写权限授予指定的用户

GRANT READ,WRITE ON DIRECTORY recv_area TO hanjs;

GRANT READ,WRITE ON DIRECTORY send_area TO hanjs;

--GRANT EXECUTE ON utl_file TO hanjs;

以hanjs登录,进行测试。

确认目录设置信息

SELECT * FROM ALL_DIRECTORIES;

1 SYS RECV_AREA d:test
2 SYS SEND_AREA d:test
--写文件的例子
CREATE OR REPLACE PROCEDURE CREATE_DIR_WRITE_SAMPLE
AS
vHandle UTL_FILE.FILE_TYPE;
vDirname Varchar2(250);
vFilename Varchar2(250);
vOutput Varchar2(32767);
BEGIN
vDirname := 'SEND_AREA'; --大写的目录定义名
vFilename:='test.txt';
vHandle := UTL_FILE.FOPEN(vDirname,vFilename,'w',32767);
vOutput := 'my utl_file test';
UTL_FILE.PUT_LINE(vHandle,vOutput);
UTL_FILE.FCLOSE(vHandle);
END;
--读文件的例子
create or replace procedure loadfiledata(p_filename varchar2)
As
v_filehandle utl_file.file_type; --定义一个文件句柄
v_text varchar2(100); --存放文本
v_name test_loadfile.name%type;
v_addr_jd test_loadfile.addr_jd%type;
v_region test_loadfile.region%type;
v_firstlocation number;
v_secondlocation number;
v_totalinserted number;
begin
if (p_filename is null) then
--goto to_end;
Return;
end if;
v_totalinserted:=0;
/*open specified file*/
v_filehandle:=utl_file.fopen('RECV_AREA',p_filename,'r');
loop
begin
utl_file.get_line(v_filehandle,v_text);
exception
when no_data_found then
exit;
end ;
v_firstlocation:=instr(v_text,',',1,1);
v_secondlocation:=instr(v_text,',',1,2);
v_name:=substr(v_text,1,v_firstlocation-1);
v_addr_jd:=substr(v_text,v_firstlocation+1,v_secondlocation-v_firstlocation-1);
v_region:=substr(v_text,v_secondlocation+1);
/*插入数据库操作*/
insert into test_loadfile values (v_name,v_addr_jd,v_region);
commit;
end loop;
/*
<>

null;
*/
end loadfiledata;

[@more@]

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/7659204/viewspace-897755/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/7659204/viewspace-897755/

你可能感兴趣的:(利用utl_file读写文件)