Goal
1) Mastering the role of the file class
2) You can use the method in the file class to read and write Files.
File class
The only class that is related to the File. Use the file class to create or delete operations, and to use the file class, first observe the method of constructing the file class.
Public file (String pathname); The path must be set when instantiating the file class.
Constant::
public Final String pathseparator;
The constants that are defined by static final are used clearly, why lowercase is used Here. This is actually a legacy of Java's History.
Instance action one: Create a new File.
To create a file:
public Boolean throws Ioexcetion
You can create files with these methods, but be aware of exception handling .
Create a file in the D drive:
Importjava.io.File;Importjava.io.IOException; public classfiledemo01{ public Static voidmain (String Args[]) { File f = new File ("d:\\test.txt"); Instantiate the object of the file class, give the path try { F.createnewfile (); //create a file, create it according to the given path}Catch (ioexception e) { e.printstacktrace (); //Output Exception Information } }};
Operation Result:
Step: First create the file object, when creating the object to give the path of the files, and then use this object to call the Creatnewfile () method, Note that the method should be called exception handling .
The above completion of the file creation function, but the development of the above program writing will definitely error, in each operating system, the path delimiter is not the Same. For example:
Windows uses a backslash: "\"
Use forward slash in Linux: "/"
For Java portability enhancements, It's a good idea to let the operating system automatically use separators .
package Thread1; Import java.io.File; Import java.io.IOException; public class demo1{ publicstaticvoid main (String args[]) { System.out.println ("pathseparator:" + file.pathseparator); // calling Static constants System.out.println ("separator:" + file.separator); // Calling Static constants }}
Operation Result:
Pathseparator:;separator:\
To maintain portability, you should use constants in the file class when you Write. Modify the previous Program.
packageThread1;Importjava.io.File;Importjava.io.IOException; public classdemo1{ public Static voidmain (String Args[]) {File f=NewFile ("d:" + File. Separator + "test.txt");//instantiating an object of the file class Try{f.createnewfile (); //creates a file that is created according to the given path}Catch(ioexception E) {e.printstacktrace (); //Output Exception Information } }}
Note: Be sure to note the delimiter when manipulating the file, using File.separator.
Deletes a specified file
Delete File method:
public Boolean Delete ();
Delete the previously created File.
package Thread1; Import java.io.File; Import java.io.IOException; public class demo1{ publicstaticvoid main (String args[]) { = new File ("d:" +file.separator+ "test.txt"); Instantiate the object of the file class F.delete (); Delete file }}
Operation Result:
You did delete the File.
at this point the file is actually deleted, but it is best to determine whether the file is present before deleting it.
In the file class, you can use the exists () method to determine whether a file exists .
public Boolean exists ();
Use the above code to enhance the previous Program.
packageThread1;Importjava.io.File;Importjava.io.IOException; public classdemo1{ public Static voidmain (String Args[]) {File f=NewFile ("d:" +file.separator+ "test.txt");//instantiating an object of the file class if (f.exists ()) {//delete if file existsF.delete ();//Deleting Files } ElseSystem.out.println ("file does not exist"); }}
Operation Result:
File does not exist
The file does not exist because it was previously deleted.
Integrated creation, deletion of file operations
Requirement: given a path, if the file exists delete, does not exist, create it.
Importjava.io.File;Importjava.io.IOException; public classfiledemo06{ public Static voidmain (String Args[]) {File f=NewFile ("d:" +file.separator+ "test.txt");//instantiating an object of the file class if(f.exists ()) {//Delete If the file existsF.delete ();//Deleting Files}Else{ Try{f.createnewfile (); //creates a file that is created according to the given path}Catch(ioexception E) {e.printstacktrace (); //Output Exception Information } } }};
Tip: the suffix for the file is Optional.
Create a folder
Use the mkdir () method to create a folder,
public boolean mkdir ();
Instance
Import java.io.File; Import java.io.IOException; public class filedemo07{ publicstaticvoid main (String args[]) { New File ("d:" +file.separator+ "mldn"); // instantiating an object of the file class F.mkdir (); // Create a folder }};
Run result: a folder named Mldn was created Successfully.
Lists all files for the specified directory.
If you give a directory, you can list everything in the directory, but there are two methods listed:
1, returned as an array of strings.
public String [] List ();
2, returned as a file array:
Pulbic File [] listfiles ();
Action one: list () method:
packageThread1;Importjava.io.File;Importjava.io.IOException; public classdemo1{ public Static voidmain (String Args[]) {File f=NewFile ("d:" +file.separator);//instantiating an object of the file class String str[] = f.list (); List content in a given directory for(inti=0;i<Str.length; i++) {System.out.println (str[i]); } }}
Operation Result:
$RECYCLE. BIN360SOFTMOVEBDSOFTMGRDATACONFIG.MSIFDOWNLOADGSP Platform GS Management Kit Msocacheprogram Filessystem Volume INFORMATIONTRAININGPACKAGE_DNATRAININGPACKAGE_ZCGL long its training office software My Documents sogou high-speed download funny file Cleanup. bat programming software Blue Bridge Cup questions
The above only lists all the file names .
Action 2, listed using the Listfiles () method.
packageThread1;Importjava.io.File;Importjava.io.IOException; public classdemo1{ public Static voidmain (String Args[]) {File f=NewFile ("d:" +file.separator);//instantiating an object of the file class File files[] = F.listfiles (); To list all the contents, note that a Files object array is required to accept this return array. for(inti=0;i<files.length;i++) {System.out.println (files[i]); } }}
Operation Result:
D:\ $RECYCLE. BIND:\360SOFTMOVED:\BDSOFTMGRDATAD:\CONFIG.MSID:\FDOWNLOADD:\GSP Platform D:\GS Management Kit D:\msocached:\program Filesd:\System Volume informationd:\trainingpackage_dnad:\trainingpackage_zcgld:\ Long Training d:\ Office software d:\ My Documents d:\ sogou high-speed download d:\ funny d:\ file Cleanup. batd : \ Programming software d:\ Blue Bridge Cup questions
the full path is listed at this time . This is very easy for the program itself to Operate.
Determines whether a given path is a directory.
Use the method directly in the file class : Public boolean isdirectory ();
packageThread1;Importjava.io.File;Importjava.io.IOException; public classdemo1{ public Static voidmain (String Args[]) {File f=NewFile ("d:" +file.separator);//instantiating an object of the file class if(f.isdirectory ()){//determine if it is a directoryThe System.out.println (f.getpath () + "path is the Directory. ") ; }Else{System.out.println (f.getpath ()+ "path is not a directory. ") ; } }}
Operation Result:
The d:\ path is a directory.
List all contents of the specified directory
If a directory is given, all the files of the directory are listed, but there may be subfolders and subfolders in the Column.
Should take the form of Recursion.
packageThread1;Importjava.io.File;Importjava.io.IOException; public classdemo1{ public Static voidmain (String Args[]) {File my=NewFile ("d:" + file.separator+ "Fdownload") ;//Action Path Print (my); } public Static voidPrint (file File) {//recursive Invocation if(file!=NULL){//determines whether an object is empty if(file.isdirectory ()) {//If the directory File f[] = File.listfiles (); List all the files if(f!=NULL){//determine if this directory can be listed for(inti=0;i<f.length;i++) { print (f[i]); //because The given path is likely to be a directory, so continue to judge, continue to Recursion. } } }Else{System.out.println (file); //Output Path } } }};
Operation Result:
d:\FDownload\ Merge \0001. Chinese network tv-"poetry china" The origin of the first episode of the poem [hd version].mp4d:\fdownload\ merge \0001. Chinese network tv-"poetry china" Seventh episode of affection poems [hd version] . mp4d:\fdownload\ merge \0001. China Network TV station-"poetry china" The third episode of Spring River Flower Moonlight [hd version].mp4d:\fdownload\ merge \0001. Chinese network TV station-"chinese poetry" The second set of Maple Bridge Night Park [hd version].mp4d:\fdownload\ merge \0001. Chinese network TV station-"poetry china" Fifth set of folk songs [hd version].mp4d:\fdownload\ merge \0001. China Network TV station- "poetry china" Sixth episode nostalgic poem [hd version].mp4d:\fdownload\ merge \0001. Chinese network TV station-"poetry china" fourth set yellow Crane tower and Stork house [HD version].mp4
This is used here to determine if the path is a folder: isdirection (). List folder under directory Method: listfiles (). and Recursion.
Java IO operations---the File class