当前位置: 移动技术网 > IT编程>数据库>Oracle > oracle中utl_file包读写文件操作实例学习

oracle中utl_file包读写文件操作实例学习

2017年12月12日  | 移动技术网IT编程  | 我要评论

关东大先生演员表,河道清淤机械,洞口县人民政府

在oracle中utl_file包提供了一些操作文本文件的函数和过程,学习了一下他的基本操作
1.创建directory,并给用户授权
复制代码 代码如下:

--创建directory
create or replace directory testfile as '/home/oracle/zxx/test';
--给用户授权
grant read, write on directory testfile to zxx;

详细介绍
http://download.oracle.com/docs/cd/b19306_01/appdev.102/b14258/u_file.htm
2.写入操作
复制代码 代码如下:

---测试写入
declare
filehandle utl_file.file_type; --句柄
begin
filehandle := utl_file.fopen('testfile','hello.txt','w'); --打开文件
utl_file.put_line(filehandle,'hello oracle!');--写入一行记录
utl_file.put_line(filehandle,'hello world!');
utl_file.put_line(filehandle,'你好,胖子!');
utl_file.fclose(filehandle);--关闭句柄
end;

备注:
fopen有一个参数max_linesize,下面是原文解释
maximum number of characters for each line, including the newline character, for this file (minimum value 1, maximum value 32767). if unspecified, oracle supplies a default value of 1024.
3.读取操作
复制代码 代码如下:

--测试读取
set serveroutput on;
declare
filehandle utl_file.file_type;
filebuffer varchar2(500);
begin
filehandle := utl_file.fopen('testfile','hello.txt','r');
if utl_file.is_open(filehandle) then
dbms_output.put_line('file is open!');
end if;
loop
begin
utl_file.get_line(filehandle,filebuffer);
dbms_output.put_line(filebuffer);
exception
when no_data_found then
exit ;
when others then
dbms_output.put_line('exception1:'||substr(sqlerrm, 1, 100)) ;
end;
end loop;
utl_file.fclose(filehandle);
if utl_file.is_open(filehandle) then
dbms_output.put_line('file is open!');
else
dbms_output.put_line('file is close!');
end if;
utl_file.fcopy('testfile', 'hello.txt', 'testfile', 'hello.dat');--复制
utl_file.fcopy('testfile', 'hello.txt', 'testfile', 'hello2.dat');
utl_file.fcopy('testfile', 'hello.txt', 'testfile', 'hello.xls');
utl_file.frename('testfile','hello.xls','testfile','frenamehello.xls',true);--重命名
utl_file.fremove('testfile', 'hello2.dat');--删除文件
exception
when others then
dbms_output.put_line('exception2:'||substr(sqlerrm, 1, 100)) ;
end;

4.判断文件是否存在(读,重命名,复制,删除都要判断文件是否存在)
复制代码 代码如下:

--判断文件是否存在
declare
ex boolean;--文件是否存在
flen number;--文件长度? 这个地方不知道怎么理 (原文 file_length the length of the file in bytes. null if file does not exist.)
bsize number;--文件大小
begin
utl_file.fgetattr('testfile', 'hello.txt', ex, flen, bsize);
if ex then
dbms_output.put_line('file exists');
else
dbms_output.put_line('file does not exist');
end if;
dbms_output.put_line('file length: ' || to_char(flen));
dbms_output.put_line('block size: ' || to_char(bsize));
end fgetattr;

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网