Document manipulation for Java I and O technology

  • 2020-04-01 03:25:59
  • OfStack

In Java programming, I/O operations are implemented through the classes and interfaces in the java.io package, so the first step is to import the package.

Java.io provides a File class, which is easily misunderstood. It represents a File name or directory name, not the File itself, so there is no way to manipulate the data in the File. The File class provides a sequence of operations on files: delete files, create directories, query File sizes, and so on. To manipulate file data, you need a stream object, which I won't cover here.

The following is a class called FileExtension to encapsulate the various operations in the File class, through this example I hope you good use of the File class, here I only provide DeleteFile implementation. This example is from the Java instance technology manual.


public class FileExtension {

    

public static void DeleteFile(String filename){} //This function deletes 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 the Java wrapper for File makes it very easy to use. If you are interested, you can add some functions such as CreateDir, ListDir, FileSize and so on, which will help you.


Related articles: