file class basic operations
In Linux, everything is file, so file operations are the basis.
The file class is provided in Java to provide some basic operations on files, and the first thing to do in a new class is to look at the API documentation
The file class's API documentation describes the path to the files in Linux or Unix under '/' windows with ' \ ';
In the last line of the API, there is a sentence stating that
Instances of File the class was immutable; that's, once created, the abstract pathname represented by a File object wil L never change.
This means that a file cannot be pointed to other files once it is instantiated. Only one file can be instantiated here to open the file
Here are the basic operations of some file classes.
Public classFiledemo { Public Static voidMain (string[] args) {//constructor FunctionFile File =NewFile ("G:\\text.txt"); //determine if a file or directory exists if(!file.exists ()) File.mkdir (); //File.mkdirs () ElseFile.delete (); //is a directory if the directory returns true if it is not a directory or directory does not exist return is falseSystem.out.println (File.isdirectory ()); //whether it is a fileSystem.out.println (File.isfile ()); //another constructorFile file2 =NewFile ("g:\\", "Test1.txt"); if(!file2.exists ())Try{file2.createnewfile (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } ElseFile2.delete (); //APIs for commonly used file objectsSystem.out.println (file);//content of file.tostring ()System.out.println (File.getabsolutepath ()); System.out.println (File.getname ()); System.out.println (File2.getname ()); System.out.println (File.getparent ()); System.out.println (File2.getparent ()); System.out.println (File.getparentfile (). GetAbsolutePath ()); }}
Get all the files in a directory
Public voidshowdirectory (File dir) {//Determine if dir is a directory if(!dir.exits () | | |dir.isdirectory ()) { Throw NewException (dir+ "Not directory"); } //Traverse DirectoryFile[] Files=Dir.listfiles (); for(File file:files) {if(File.isdirectory ()) showdirectory (file); ElseSystem.out.println (file. GetAbsolutePath()); }}
The above is the basic content of the file class
Java Learning Program November 28-December 1