5

试图检查我要读取的文件是否存在。

4

3 回答 3

11

这是另一种方法:

  1. 包的使用BFILEfileexists功能dbms_lob

    create or replace function FileExists(
       p_DirName in varchar2,     -- schema object name
       p_FileName in varchar2
     ) return number
    is
      l_file_loc bfile;
    begin
      l_file_loc := bfilename(upper(p_DirName), p_FileName);
      return dbms_lob.fileexists(l_file_loc);  -- 1 exists; 0 - not exists
    end;
    
  2. 使用包fgetattr功能utl_file

    create or replace function FileExists(
      p_DirName in varchar2,     -- schema object name
      p_FileName in varchar2
    ) return number
    is
      l_fexists boolean;
      l_flen   number;
      l_bsize  number;
      l_res    number(1);
    begin
      l_res := 0;
      utl_file.fgetattr(upper(p_DirName), p_FileName, l_fexists, l_flen, l_bsize);
      if l_fexists
      then
        l_res := 1;
      end if;  
      return l_res;
    end;
    
于 2012-12-21T06:03:31.163 回答
2

创建一个检查文件是否存在的函数相当容易,只需尝试打开它并捕获任何异常(此示例函数取自AskTom

CREATE OR REPLACE FUNCTION file_exists(p_fname IN VARCHAR2) RETURN BOOLEAN
AS
  l_file UTL_FILE.FILE_TYPE;
BEGIN
  l_file := UTL_FILE.FOPEN(SUBSTR( p_fname, 1, instr(p_fname,'/',-1) ),
                           SUBSTR( p_fname, instr( p_fname, '/', -1)+1 ), 'r' );   
  UTL_FILE.FCLOSE( l_file );
  RETURN TRUE;
EXCEPTION
  WHEN UTL_FILE.INVALID_PATH      THEN RETURN FALSE;
  WHEN UTL_FILE.INVALID_OPERATION THEN RETURN FALSE;
END;
/

然后你可以使用;

IF ( file_exists( 'MED_LIST_19_OCT_12.csv' ) )
...
于 2012-12-20T22:05:26.157 回答
1

使用UTL_FILE.FGETATTR功能。此功能专为此目的而设计。

句法:

UTL_FILE.FGETATTR(
   location     IN VARCHAR2, 
   filename     IN VARCHAR2, 
   fexists      OUT BOOLEAN, 
   file_length  OUT NUMBER, 
   block_size   OUT BINARY_INTEGER);

例子:

DECLARE
  fexists      BOOLEAN;
  file_length  NUMBER;
  block_size   BINARY_INTEGER;
BEGIN

    UTL_FILE.FGETATTR('MY_ORA_DIRECTORY', 'my_file_name.csv', fexists, file_length, block_size);
    IF fexists THEN
       -- Do something
       -- ...
    END IF;

END IF;

Oracle 文档: https
://docs.oracle.com/database/121/ARPLS/u_file.htm#ARPLS70915 另一个有用的链接: https ://www.foxinfotech.in/2018/09/how-to-check-if -file-exists-in-pl-sql.html

于 2019-03-12T11:11:25.017 回答