Java (java io-File class), io-
1. In the entire io package, the only class that indicates the File itself is the File class. You can use the File class to create or delete files. To use the File class, first observe the construction method of the File class. The common construction methods of this class are as follows: public File (String pathname)-> when instantiating the File class, you must set the path. Ii. Main methods and constants in the File class
No. |
Method or constant |
Type |
Description |
1 |
Public static final String pathSeparator |
Constant |
It indicates the path separator (windows is: ";") |
2 |
Public static final String separator |
Constant |
Path separator ("\" for windows) |
3 |
Public File (String pathname) |
Structure |
Create a File object and pass in the complete path |
4 |
Public boolean createNewFile () throws IOException |
Normal |
Create a new file |
5 |
Public boolean delete () |
Normal |
Delete an object |
6 |
Public boolean exists () |
Normal |
Determine whether a file exists |
7 |
Public boolean isDirectory () |
Normal |
Determines whether the specified path is a directory. |
8 |
Public long length () |
Normal |
Size of the returned File |
9 |
Public String [] list () |
Normal |
Lists all the contents of a specified directory, but lists the names |
10 |
Public File [] listFiles () |
Normal |
Lists All contents of a specified directory, and lists the paths. |
11 |
Public boolean mkdir () |
Normal |
Create a directory |
12 |
Public boolean renameTo (File dest) |
Normal |
Rename an existing file |
3. Create a new file 3.1 and directly create the file:
Package com. pb. file. demo1; import java. io. file; import java. io. IOException; public class FileDemo1 {public static void main (String [] args) {File file = new File ("d:/test.txt "); // declare a file object try {boolean flag = file. createNewFile (); // if (flag) {System. out. println ("File Created successfully");} else {System. out. println ("file creation failed") ;}} catch (IOException e) {e. printStackTrace ();}}}
3.2 In different operating systems, the path separator is different
In windows, the backslash bar is used to indicate the directory separator "\".
In linux, the forward and oblique bars are used to represent the directory separator "/".
Package com. pb. file. demo1; import java. io. file; public class FileDemo2 {public static void main (String [] args) {System. out. println (File. pathSeparator); // call the static constant System. out. println (File. separator); // call a static constant }}
Result:
;\
3.3 modify the code for creating a file
Use static constants to connect
Package com. pb. file. demo1; import java. io. file; import java. io. IOException; public class FileDemo1 {public static void main (String [] args) {String path ="D:" + File. separator + "test1.txt";File file = new File (path); // declare a file object try {boolean flag = File. createNewFile (); // if (flag) {System. out. println ("File Created successfully");} else {System. out. println ("file creation failed") ;}} catch (IOException e) {e. printStackTrace ();}}}
Iv. delete file 4.1. Do not judge whether the file exists or not to delete it directly
Package com. pb. file. demo1; import java. io. file; import java. io. IOException; public class FileDemo3 {public static void main (String [] args) {String path = "d:" + File. separator + "test.txt"; File file = new File (path); // declare a file object boolean flag = File. delete (); // delete objects by path. The returned type is Boolean if (flag) {System. out. println ("File deleted successfully");} else {System. out. println ("file deletion failed ");}}}
4.2 determine whether the file exists and then delete it
Package com. pb. file. demo1; import java. io. file; import java. io. IOException; public class FileDemo3 {public static void main (String [] args) {String path = "d:" + File. separator + "test.txt"; File file = new File (path); // declare a file object if (File. exists () {boolean flag = file. delete (); // delete objects by path. The returned type is Boolean if (flag) {System. out. println ("File deleted successfully");} else {System. out. println ("file deletion failed") ;}} else {Sys Tem. out. println ("the file does not exist! ");}}}
4.3 create and delete instances based on the preceding two examples.
Package com. pb. file. demo1; import java. io. file; import java. io. IOException; public class FileDemo4 {public static void main (String [] args) {String path = "d:" + File. separator + "test.txt"; File file = new File (path); // declare a file object if (File. exists () {// determine whether a file exists. If yes, delete the file. delete (); System. out. println ("file exists. Deleted successfully! ");} Else {// determine whether the file exists. If not, create try {file. createNewFile (); System. out. println (" the file does not exist. The file is created successfully! ") ;}Catch (IOException e) {e. printStackTrace ();}}}}
5. Create a folder 5.1 and a folder mkdir
Package com. pb. file. demo1; import java. io. file; import java. io. IOException; public class FileDemo5 {public static void main (String [] args) {String path = "d:" + File. separator + "test"; File file = new File (path); // declare a File object if (! File. exists () {boolean flag = file. mkdir (); // create a folder if (flag) {System. out. println ("folder created successfully") ;}} else {System. out. println ("a folder with this name already exists! ");}}}
5.2 create a multi-layer folder mkdirs
Package com. pb. file. demo1; import java. io. file; import java. io. IOException; public class FileDemo5 {public static void main (String [] args) {String path = "d:" + File. separator + "test" + File. separator + "test1" + File. separator + "test2"; File file = new File (path); // declare a File object if (! File. exists () {boolean flag = file. mkdirs (); // create a folder if (flag) {System. out. println ("folder created successfully") ;}} else {System. out. println ("a folder with this name already exists! ");}}}
5.3 list all contents in the directory
Package com. pb. file. demo1; import java. io. file; import java. io. IOException; public class FileDemo6 {public static void main (String [] args) {String path = "f:" + File. separator; File file = new File (path); // declare a File object System. out. println ("============== list only the names of folders and files ====================== "); string [] str = file. list (); // list all content folders and files in the directory // This method only lists the folder and file names for (int I = 0; I <str. length; I ++) {System. out. println (str [I]. toString ();} System. out. println ("================= list the paths, folders, and files = "); file [] file1 = file. listFiles (); // list all content folders and files in the directory // This method lists the paths, folders, and file names for (int I = 0; I <file1.length; I ++) {System. out. println (file1 [I]. toString ());}}}
Result:
=================List only the names of folders and files =========================$ RECYCLE. BINdownloadeclipse-keplerhtmljavajava workshop learning notes shopSystem Volume Informationttoolsvm software ================== name of the List paths, folders, and files ======== ========== f: \ $ RECYCLE. BINf: \ downloadf: \ eclipse-keplerf: \ htmlf: \ javaf: \ java webf: \ javascriptf: \ javastudyf: \ jqueryf: \ jsf: \ jspf: \ jsptestf: \ linuxf: \ ORACLEf: \ oracle Study Notes f: \ shopf: \ System Volume Informationf: \ tf: \ toolsf: \ vmf: \ Software
5.3 Add a file or directory
First, determine whether a directory is provided.
Package com. pb. file. demo1; import java. io. file; import java. io. IOException; public class FileDemo7 {public static void main (String [] args) {String path = "g:" + File. separator; File file = new File (path); // declare a file object if (File. isDirectory () {System. out. println (file. getPath () + "is the directory! ");} If (file. isFile () {System. out. println (file. getPath () +" is a file! ");}}}
Package com. pb. file. demo1; import java. io. file; import java. io. IOException; public class FileDemo7 {public void print (File file) {if (file. exists () {// checks whether a specified directory or file exists in System. out. println ("=============== path existence ========="); if (file. isDirectory () {System. out. println (file. getPath () + "is the directory! All files under the directory will be listed! ================ "); File [] f = file. listFiles (); // All contents in the directory are listed in the directory for (int I = 0; I <f. length; I ++) {if (f [I]. isDirectory () {System. out. println (f [I] + "\ t is the directory! ");} Else {System. out. println (f [I] +" \ t is a file! ") ;}} Else {// print the path information System. out. println (file +" \ t is a file if it is not a directory! ") ;}} Else {System. out. println (file +" =============== the path does not exist! ============== ") ;}} Public static void main (String [] args) {String path =" g: "+ File. separator; File file = new File (path); // declare a File object FileDemo7 fd = new FileDemo7 (); fd. print (file );}}
Result:
================= Path existence ============ g: \ is a directory! All files under the directory will be listed! ================== G: \ $ RECYCLE. BIN is the directory! G: \ Adobe Dreamweaver CS5 is a directory! G: \ Adobe Dreamweaver CS5.rar is a file! G: \ atm is the directory! G: \ atm.rar is a file! G: \ eclipse is the directory! G: \ eclipse-kepler is the directory! G: \ html is the directory! G: \ java is the directory! G: \ jsp is the directory! G: \ orcale is the directory! G: \ SqlHistory. xml is a file! G: \ System Volume Information is a directory! G :\~ 1 is the directory! G: \ The book is a directory! G: \ stop .. bat is a file! G: \ Start. bat is a file! G: \ the source is a directory! G: \ third-party controls are Directories!
6. Other Methods
Package com. pb. file. demo1; import java. io. file; import java. io. IOException; import java. text. simpleDateFormat; import java. util. date;/** file operation methods */public class FileMethods {public static void main (String [] args) throws IOException {// instantiate the File class object File f = new File ("d:" + File. separator + "test" + File. separator + "hello.txt"); // file File Attribute System. out. println ("file name:" + f. getName (); // relative path: System. out. println ("relative path:" + F. getParent (); // absolute path System. out. println ("absolute path:" + f. getAbsolutePath (); // obtain the parent directory of the file. The parent directory is System. out. println ("upper-level directory" + f. getParent (); // whether the current file contains System. out. println (f. exists ()? "File": "file does not exist"); // is it a file System. out. println (f. isFile ()? "Is a file": "Not a file"); // The file length is System. out. println ("file length:" + f. length (); // whether it is a file System. out. println (f. isDirectory ()? "Is a folder": "Not a folder"); // can I read System. out. println (f. canRead ()? "File readable": "file unreadable"); // can I write System. out. println (f. canRead ()? "File writable": "file writable"); // The last modification time SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss "); date date = new Date (f. lastModified (); System. out. println ("Last modified time:" + sdf. format (date); // create if (! F. exists () {// create f if the file does not exist. createNewFile (); System. out. println ("Create File");} else {// Delete f. delete (); System. out. println ("delete file ");}}}