[ABAP] How do I perform binary file I/O and serialization in ABAP?

To perform binary file I/O and serialization in ABAP, you can use the following steps:

  1. Create a binary file:

    • Use the class cl_gui_frontend_services to get the file path and name.
    • Open the file using the function module GUI_DOWNLOAD.
    • Write the binary data into the file using the function module GUI_DOWNLOAD.
  2. Read a binary file:

    • Use the class cl_gui_frontend_services to get the file path and name.
    • Open the file using the function module GUI_UPLOAD.
    • Read the binary data from the file using the function module GUI_UPLOAD.
  3. Serialize and deserialize objects:

    • Implement the IF_SERIALIZABLE_OBJECT interface in your class to make it serializable.
    • Use the class cl_abap_typedescr to get the description of the class.
    • Use the class cl_abap_serializer to serialize the object into a binary string using the method serialize.
    • Use the class cl_abap_deserializer to deserialize the binary string back into an object using the method deserialize.

Here is an example of how to perform binary file I/O and serialization in ABAP:

 1DATA: lv_file TYPE string,
 2      lv_data TYPE xstring,
 3      lo_serializer TYPE REF TO cl_abap_serializer,
 4      lo_deserializer TYPE REF TO cl_abap_deserializer,
 5      lo_object TYPE REF TO zcl_example_class.
 6
 7" Binary file I/O
 8lv_file = 'C:\temp\example.bin'.
 9
10" Write binary data to file
11CALL FUNCTION 'GUI_DOWNLOAD'
12  EXPORTING
13    filename = lv_file
14  TABLES
15    data_tab = lt_data.
16
17" Read binary data from file
18CALL FUNCTION 'GUI_UPLOAD'
19  EXPORTING
20    filename = lv_file
21  TABLES
22    data_tab = lt_data.
23
24" Serialization
25lo_serializer = cl_abap_serializer=>create_serializer( ).
26lo_serializer->serialize( EXPORTING iv_object = lo_object
27                           RECEIVING rv_data = lv_data ).
28
29" Deserialization
30lo_deserializer = cl_abap_deserializer=>create_deserializer( ).
31lo_deserializer->deserialize( EXPORTING iv_data = lv_data
32                              RECEIVING rv_object = lo_object ).

Note: Replace zcl_example_class with the name of your class.