Reading/Writing files using PL/SQL
Posted by Rajkiran Ghanta on November 24, 2007
Prior to Oracle 9i R2, each directory to be accessed by utl_file must be specified in the init.ora parameter and the database needs to be restarted inorder to make the directory effective.
From 9i R2, instead of specifying directory in the in the init.ora file, a directory object can be used.
Directory object can be created using the create directory command. You need to check with your admin to make sure the directory exists and has correct permissions at the os level. Also, DBA user can control the permissions on the directory object by granting read and write privileges only to the required users.
Examples:
1) Using directory specified in the utl_file_dir parameter in init.ora file
Add the directory e.g. /u01/utilout to the utl_file_dir parameter in the init.ora file and bounce the database.
Then use the directory to read and write the files using UTL_FILE package.
DECLARE
v_out_file UTIL_FILE.FILE_TYPE;
BEGIN
v_out_file := UTL_FILE.FOPEN(‘/u01/utilout’,'test.txt’, ‘W’);
UTL_FILE.PUT_LINE (v_out_file, ‘Test Message1′);
UTL_FILE.PUT_LINE (v_out_file, ‘Test Message2′);
UTL_FILE.FCLOSE(v_out_file);
END;
/
2) Using directory object
create directory object using create directory command and grant read, write to the user as shown below :
create directory UTIL_OUT as ‘/u01/utilout’;
grant read, write on directory UTIL_OUT to testuser;
Then use the directory object name to read and write the files using UTL_FILE package.
DECLARE
v_out_file UTIL_FILE.FILE_TYPE;
BEGIN
v_out_file := UTL_FILE.FOPEN(‘UTIL_OUT’,'test.txt’, ‘W’);
UTL_FILE.PUT_LINE (v_out_file, ‘Test Message1′);
UTL_FILE.PUT_LINE (v_out_file, ‘Test Message2′);
UTL_FILE.FCLOSE(v_out_file);
END;
/
The files created by UTIL_FILE package will have the permissions as per the umask settings of the oracle user.These file permissions can be changed manually after the files are created using chown and chgrp commands.
Incase you need to have the files created automatically with different permissions, you can try changing the umask permissions of the oracle user.