In java programming, I/O operations are implemented through classes and interfaces in the java.io package. Therefore, the first step we have to do is to import this package.
java.io provides a File class, which is easy to misunderstand. It represents a file name or directory name, not the file itself, so the data in the file cannot be operated through this class. The File class provides a series of functions for file operations: deleting files, creating directories, querying file sizes, etc. If you want to operate on file data, you need a stream object, which will not be introduced here for the time being.
Below, a class called FileExtension is used to encapsulate various operations in the File class. Through this example, I hope you can use the File class well. Here I only provide the implementation of DeleteFile. This example is quoted from the book "Java Example Technical Manual".
public class FileExtension { /** * delete a specify file * @param filename : specify a file */ public static void DeleteFile(String filename){} //The function of this function is to delete a specified existing file protected static void fail (String msg) throws IllegalArgumentException{ throw new IllegalArgumentException(msg); }}
The implementation of DeleteFile is as follows:
public static void DeleteFile(String filename){ File file = new File(filename); if(!file.exists()) fail("Delete: no such file or directory:" + filename); if(!file.canWrite( )) fail("Delete: write protected: " + filename); if(file.isDirectory()){ String[] files = file.list(); if(files.length > 0) fail("Delete: directory not empty: " + filename); } boolean success = file.delete(); if(!success) fail("Delete: deletion failed"); }
If you read the above example in detail, you will find that java's packaging of File makes it very easy for us to use. If you are interested, you can add some functions, such as CreateDir, ListDir, FileSize and other functions. will help you.