UTL_FILE Package
UTL_FILE package built into the oracle database allows PL/SQL programs to read and write to an operating system file.

The UTL FILE package has been available since PL/SQL 2.3 and has become the easiest interface to use in generating flat files from the database to get around the limitations of DBMS_OUTPUT package. To read or write to a file using UTL_FILE, you call FOPEN, which returns a file handle for use in subsequent calls. For example procedures like PUT_LINE can be used to write a line to the open file and GET_LINE can be used to read a line from the file file.

UTL_FILE.FOPEN : FOPEN function allows you to open a file. It accepts the location, filename, openmode and max line size as the arguments and returns the file handle to be used in subsequent calls. 

Syntax : UTL_FILE.FOPEN (location     IN VARCHAR2,filename     IN VARCHAR2,open_mode    IN VARCHAR2,max_linesize IN BINARY_INTEGER) RETURN file_type;

Open Mode flags

  • r -- read text
  • w -- write text
  • a -- append text
  • rb -- read byte mode
  • wb -- write byte mode
  • ab -- append byte mode

UTL_FILE Sample 

BEGIN
    output_file := utl_file.fopen (folder, file_name, filemode);
    utl_file.put_line (output_file, extract_record);
    utl_file.fclose(output_file);

EXCEPTION
    WHEN utl_file.invalid_path THEN
        v_status := -29280;
        v_msg := 'Error :Invalid Path- Check the  UTL_FILE_DIR parameter';
    WHEN utl_file.invalid_mode THEN
        v_status := -29281;
        v_msg := 'Error :Invalid Mode';
    WHEN utl_file.invalid_filehandle THEN
        v_status := -29282;
        v_msg := 'Error :Invalid File Handle';
    WHEN utl_file.invalid_operation THEN
        v_status := -29283;
        v_msg := 'Error : Invalid file operation';
    WHEN utl_file.read_error THEN
        v_status := -29284;
        v_msg := 'Error :Read Error';
    WHEN utl_file.write_error THEN
        v_status := -29285;
        v_msg := 'Error :Read Error';
    WHEN utl_file.internal_error THEN
        v_status := -29286;
        v_msg := 'Error :Invalid Error';
    WHEN OTHERS THEN
        v_status := -99999;
        v_msg := 'Error :utl_file.other_error';
END;
/