The following examples show how to use the IFSFile class:
// Create an AS400 object. This new // directory will be created on this // iSeries. AS400 sys = new AS400("mySystem.myCompany.com"); // Create a file object that // represents the directory. IFSFile aDirectory = new IFSFile(sys, "/mydir1/mydir2/newdir"); // Create the directory. if (aDirectory.mkdir()) System.out.println("Create directory was successful"); // Else the create directory failed. else { // If the object already exists, // find out if it is a directory or // file, then display a message. if (aDirectory.exists()) { if (aDirectory.isDirectory()) System.out.println("Directory already exists"); else System.out.println("File with this name already exists"); } else System.out.println("Create directory failed"); } // Disconnect since I am done // accessing files. sys.disconnectService(AS400.FILE);
When an error occurs, the IFSFile class throws the ExtendedIOException exception. This exception contains a return code that indicates the cause of the failure. The IFSFile class throws the exception even when the java.io class that IFSFile duplicates does not. For example, the delete method from java.io.File returns a boolean to indicate success or failure. The delete method in IFSFile returns a boolean, but if the delete fails, an ExtendedIOException is thrown. The ExtendedIOException provides the Java™ program with detailed information about why the delete failed.
// Create an AS400 object. AS400 sys = new AS400("mySystem.myCompany.com"); // Create a file object that // represents the file. IFSFile aFile = new IFSFile(sys, "/mydir1/mydir2/myfile"); // Delete the file. try { aFile.delete(); // The delete was successful. System.out.println("Delete successful "); } // The delete failed. Get the return // code out of the exception and // display why the delete failed. catch (ExtendedIOException e) { int rc = e.getReturnCode(); switch (rc) { case ExtendedIOException.FILE_IN_USE: System.out.println("Delete failed, file is in use "); break; case ExtendedIOException.PATH_NOT_FOUND: System.out.println("Delete failed, path not found "); break; // ... for every specific error // you want to track. default: System.out.println("Delete failed, rc = "); System.out.println(rc); } }
The Java program can optionally specify match criteria when listing files in the directory. Match criteria reduce the number of files that are returned by the server to the IFSFile object, which improves performance. The following example shows how to list files with extension .txt:
// Create the AS400 object. AS400 system = new AS400("mySystem.myCompany.com"); // Create the file object. IFSFile directory = new IFSFile(system, "/"); // Generate a list of all files with // extension .txt String[] names = directory.list("*.txt"); // Display the names. if (names != null) for (int i = 0; i < names.length; i++) System.out.println(names[i]); else System.out.println("No .txt files");