Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a file exists?

Tags:

sql

oracle

plsql

trying to check whether the file I want to read exists or not.

like image 802
eSS92 Avatar asked Dec 20 '12 21:12

eSS92


3 Answers

Here are another approaches:

  1. Using BFILE and fileexists function of dbms_lob package:

    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. Using fgetattr function of utl_file package:

    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;
    
like image 112
Nick Krasnov Avatar answered Oct 13 '22 05:10

Nick Krasnov


Use UTL_FILE.FGETATTR function. This function is designed specifically for this purpose.

Syntax:

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

Example:

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 documentation: https://docs.oracle.com/database/121/ARPLS/u_file.htm#ARPLS70915
One more useful link: https://www.foxinfotech.in/2018/09/how-to-check-if-file-exists-in-pl-sql.html

like image 27
Andre Avatar answered Oct 13 '22 06:10

Andre


Creating a function that checks if a file exists is fairly easy by just trying to open it and catching any exceptions (this example function taken from 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;
/

Then you can just use;

IF ( file_exists( 'MED_LIST_19_OCT_12.csv' ) )
...
like image 21
Joachim Isaksson Avatar answered Oct 13 '22 07:10

Joachim Isaksson