Determine whether a file is open or not in Application Server

To determine whether a file is opened or not in application server we can use the class 'CX_SY_FILE_OPEN'. By using this class we can determine whether a file is opened or not in application server as SY-SUBRC <> 0 may not provide the file's open information while we are interacting with the file. SY-SUBRC <> 0 may happens for other reasons also.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
DATA:
* First declare an object of type CX_ROOT.
OREF TYPE REF TO CX_ROOT,

* Then declare a variable of type string.
TEXT TYPE STRING.

*Now open a dataset in a TRY-CATCH block
TRY.
OPEN DATASET '/USR/SAP/TRANS/ECC1/ETC/B12008.TXT' FOR OUTPUT
IN TEXT MODE ENCODING DEFAULT

* Then in the catch block instantiate the Object.
CATCH CX_SY_FILE_OPEN INTO OREF.
* Now in 'CATCH' block use the TEXT variable to get the TEXT from the Object.
TEXT = OREF->GET_TEXT( ).

*Now if the TEXT is not initial that means the file is already opened
*else it is not opened and we have to open it
IF TEXT IS NOT INITIAL.

* If open then we can close the file
CLOSE DATASET '/USR/SAP/TRANS/ECC1/ETC/B120080627112.TXT'.

ENDIF.

ENDTRY.