In Java programming, I/O operations are implemented through the classes and interfaces in the Java.io package, so our first step is to import the package.
java.io provides a file class, which is easy to misunderstand, it represents a filename or directory name, rather than the file itself, so it is impossible to manipulate the data in the file through this class. The file class provides a sequence of functions to manipulate files: Delete files, create directories, query file sizes, and so on. If you want to manipulate the file data, you need to stream the object, which is not covered here for the time being.
The following is a package called the FileExtension class to encapsulate the various operations in the file class, and I hope that we can use the file class well, where I only provide the implementation of the DeleteFile. This example is quoted from the Java Instance Technology manual.
public class FileExtension {
/**
* Delete a specify file
* @param filename:specify a file
/
public static void DeleteFile (string filename) {}//The 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 look at the above example in detail, then you will find that Java packaging for the file makes it easy to use, if you are interested you can add some functions, such as createdir,listdir,filesize and so on some features, which will help you.