【问题标题】:Trying to read the file using utl_file method尝试使用 utl_file 方法读取文件
【发布时间】:2014-08-20 21:39:32
【问题描述】:

我正在尝试查看此文件是否存在。但我收到此错误消息。我已经检查了我获得的特权。但是这个文件在服务器端,所以我错过了什么

DECLARE
  vInHandle  utl_file.file_type;

BEGIN

  vInHandle := utl_file.fopen('IMG_UTL_DIR', 'image-file.csv', 'R');

  IF utl_file.is_open(vInHandle) THEN

      dbms_output.put_line('The File exists');

  Else

      dbms_output.put_line('The File not  exists');
  END IF;
END fopen;

错误:

ORA-29283:文件操作无效
ORA-06512:在“SYS.UTL_FILE”,第 536 行
ORA-29283: 无效的文件操作
ORA-06512: 在第 5 行

【问题讨论】:

  • 不,fopen takes the directory object name as a varchar,所以它应该被引用。该目录对象是否存在,您是否对该对象具有权限,服务器操作系统中是否存在底层目录,Oracle 是否有权访问该目录;该文件是否真的存在?你说你正在测试,但如果没有,那么它会出错。如果允许您以大写形式传递模式,我不记得了 - 文档只显示较低。
  • @AlexPoole - 我的立场是正确的。在我们的商店,DBA 拒绝让我们使用目录对象(“它们是潜在的安全风险”。WTF ?!?!?!?但我该争论谁...... :-/)所以我们仍在开放带有目录路径的文件 - 请不要问我这是如何“更好”或“更安全”的 - 这些事情超出了像我这样的凡人的范围。

标签: sql oracle plsql utl-file


【解决方案1】:

如果该文件不存在,那么您将收到该错误。使用您的代码,当文件存在时,您将获得:

anonymous block completed
The File exists

但是当文件不存在时你会得到:

Error report -
ORA-29283: invalid file operation
ORA-06512: at "SYS.UTL_FILE", line 536
ORA-29283: invalid file operation
ORA-06512: at line 6
29283. 00000 -  "invalid file operation"
*Cause:    An attempt was made to read from a file or directory that does
           not exist, or file or directory access was denied by the
           operating system.
*Action:   Verify file and directory access privileges on the file system,
           and if reading, verify that the file exists.

请注意错误描述中的“不存在的文件或目录”部分。您不能像这样测试文件的存在。据我所知,没有直接的方法来测试文件是否存在。您将不得不尝试打开文件并捕获异常。例如:

DECLARE
  vInHandle  utl_file.file_type;
  eNoFile    exception;
  PRAGMA exception_init(eNoFile, -29283);
BEGIN
  BEGIN
    vInHandle := utl_file.fopen('IMG_UTL_DIR', 'image-file.csv', 'R');
    dbms_output.put_line('The File exists');
  EXCEPTION
    WHEN eNoFile THEN
      dbms_output.put_line('The File not  exists');
  END;
END fopen;
/

anonymous block completed
The File not  exists

但是 ORA-29283 异常也可能意味着其他事情,正如描述所说,所以它并不一定意味着文件不存在 - 它可能存在但由于其他一些(与权限相关的)原因而无法访问.您还将在某种程度上掩盖实际错误的位置,并且如果您在块中有多个文件操作,那么您要么必须将每个操作包装在其自己的开始/异常/结束子块中以指定错误,否则会丢失实际的错误点。

您最好让异常自然地引发​​和报告,而不是捕获它并用可能无法被客户端检索和显示的dbms_output 消息替换它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 2016-11-12
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多