PeopleCode | Interacting with the file server by using Java Objects
A. Don’t Run Away Just Yet
If the word ‘Java’ has already scared you off, then let me know quickly reassure you before you run away forever. The good news is that you do not need to have any knowledge of Java in order to use the Java objects within PeopleCode. Think of the Java Object as just another object type, such as ‘String’, ‘Record’, or ‘File’. Once you define your Java Object variable, you can then refer to public methods and properties that are available through the class.
In this post, we will take a look at one specific Java class, the ‘io.File’ class, which provides a range of methods and properties for interacting with the file server. This post should be read in conjunction with Tip 046, which provided details of the file functions that exist within PeopleCode. If possible, try to use the native PeopleCode functions first before turning to Java.
For a full list of the Java methods and properties available in ‘io.File’, refer to the website provided in the ‘See Also’ section at the bottom of this post.
B. Delete a File
The first example shows an example of the Java ‘delete’ method for deleting a file:
Local JavaObject &javaFile; Local string &file_name, &file_path; &file_path = "/u02/app/psft/ps_cfg/appserv/PSTST/files/"; &file_name = "temp.csv"; &javaFile = CreateJavaObject("java.io.File", &file_path | &file_name); &javaFile.delete();
C. Rename a File
The next example uses the Java class to rename a file (basically to add the Operator ID and Date Time stamp to a file name of ‘REPORT’):
Local JavaObject &orig_javaFile, &new_JavaFile; Local string &orig_file_name, &new_file_name, &file_path; &file_path = "/u02/app/psft/ps_cfg/appserv/PSTST/files/"; &orig_file_name = "REPORT.csv"; &new_file_name = %OperatorId | "_REPORT_" | DateTimeToLocalizedString(%Date, "yyyyMMdd") | ".csv"; &orig_javaFile = CreateJavaObject("java.io.File", &file_path | &orig_file_name); /* Only continue if the original file exists */ If &orig_javaFile.exists() Then &new_JavaFile = CreateJavaObject("java.io.File", &file_path | &new_file_name); If &new_JavaFile.exists() Then /* Perform a delete of the new file */ &new_JavaFile.delete(); End-If; &rename = &orig_javaFile.renameTo(&new_JavaFile); End-If;
In the above example, note the use of the Java ‘exists’ method to determine whether a file already exists. We could have used the equivalent PeopleCode command here (‘FileExists’), but for the sake of featuring as much Java as possible, the Java method has been included instead.
See Also:
Tip 035: Uploading a File Attachment
Tip 046: File Manipulation in PeopleCode
Tip 060: Copying Files
For more details of the Java ‘io.File’ class, refer to http://ahchiev.com/io/10file/05file.html