Java File class learning notes 2: File class objects and common operation methods, file learning notes

Source: Internet
Author: User

Java File class learning notes 2: File class objects and common operation methods, file learning notes

1. File, relative path, and absolute path

1. File
(1) standard files: such as images and music files.
(2) directory file: a folder.
(3) virtual memory files: temporary files generated by the system during program running.

2. File Path
(1) Relative Path: compared with the path of a file, the image is to cut down the parts with the same absolute path of the two files, and the rest is the relative path.
For example:
File A is "D: \ MyDocuments \ StudySample \ src \ cn \ xmh ",
File B is "D: \ MyDocuments \ StudySample \ src \ netjava \ cjl ",
Then the path of B relative to A is "\ netjava \ cjl ";
(2) absolute path: path name counted from the disk root directory
For example, "G: \ TDDOWNLOAD \ Data Structure"

3.About System Path Separators

In Windows, the Backslash "\" is used as the path delimiter, for example, "c: \ test". However, in Java, the backslash represents the escape character, so you must use "C: \ test "indicates the path in the program. You can also use "C:/test" for path representation, which is also applicable in linux.

You can also use the constant separator defined in the File class to replace the path separator, which can be used in various systems.

For example, File file = new File ("c:" + File. separator + "test.txt ");

A separate separater indicates the root. If you create a file under the root, it is equivalent to creating a file under the root path of the program path.

Ii. File objects and common operation methods

1. The most common method is to create a file object based on a string path name.

In the entire IO package, the only class that indicates the File itself is the File class. We can use the File class to create File objects and perform various operations on File objects,

PublicFile (String pathname) specifies the path when instantiating the File class.

Example:

Import java. io. file; public class FileDemo {public static void main (String [] args) {// constructor File (String pathname) File f1 = new File ("d: \ daxiang \ 1.txt"); // File (String parent, String child) File f2 = new File ("d: \ daxiang", "2.txt "); // File (File parent, String child) File f3 = new File ("d:" + File. separator + "abc"); // separator cross-platform separator File f4 = new File (f3, "3.txt"); System. out. println (f1); // d: \ daxiang \ 1.txt System. out. println (f2); // d: \ daxiang \ 2.txt System. out. println (f3); // d: \ abcSystem. out. println (f4); // d: \ abc \ 3.txt }}

Note: when using the File class to specify the path, you must pay attention to the differences between operating systems and try to use separator for segmentation.

2. File object Operation Method

To use the File class, first observe the method of the File class. The common methods of this class are as follows:



The table above lists only some of the common methods. The following lists the common methods:

Creation Method

(1) boolean createNewFile () // method used to create a standard file

Using File file = new File (path) only specifies the path for File creation, but the file has not yet been generated. If the path does not exist, the File will not be created successfully.

(2) boolean mkdir () // create a directory (folder) based on the File object name (PATH). If it is a relative directory, the new directory is under the current directory.
(3) boolean mkdirs () // create a multi-level Directory: if the File object name has a multi-level directory, you can call this method to create a multi-level directory at a time.

Mkdirs () can be used to create multi-level folders (directories). mkdir () can only create one directory.

For example:

Filefile = new File ("c:/aa ");

File. mkdir (); // you can create an aa directory under c :/.

If there are multiple levels of directories, mkdir cannot be used to create them, for example:

Filefile = new File ("c:/aa/bb ");

File. mkdir () // cannot be created.

In this way, no directory is created, because the/tmp/one/two directory cannot be found, and false is returned.

It should be changed to: mkdirs ()

Delete Method

(1) boolean delete ()
(2) boolean deleteOnExit () // delete the file after it is used

Judgment Method

(1) boolean canExecute () // judge whether the file is executable
(2) boolean canRead () // determines whether the object is readable.
(3) boolean canWrite () // determines whether a file can be written.
(4) boolean exists () // determines whether the object exists
(5) boolean isDirectory () // checks whether the File object points to a directory, and returns a boolean value, true or false.
(6) boolean isFile () // checks whether the File pointed to by the File object is a standard File and returns a boolean value, true or false.
(7) boolean isHidden ()
(8) boolean isAbsolute () // You can also determine whether the absolute path file does not exist.

Obtain Method

(1) StringgetName () // obtain the file name (without the file path). The returned value belongs to the String type.
(2) String getPath ()
(3) String getAbsolutePath ()
(4) String getParent () // if no parent directory exists, null is returned.
(5) long lastModified () // obtain the last modification time
(6) long length () // obtain the length of the File object pointing to the File, in bytes, and return a long integer value (long)

Note: In the system, the folder (directory) size is zero, that is, no space is occupied. When length () is used, 0 is returned.
(7) boolean renameTo (File f) // rename the File specified by this abstract name

F -- the abstract path name of the new abstract path. If the name is successfully renamed, true is returned. Otherwise, false is returned.

(8) File [] listRoots () // returns an array of abstract path names, indicating that the abstract path name is in the directory and meets the requirements of the files and directories of the specified filter.
(9) String [] list ()
(10) String [] list (FilenameFilter filter)

The simple implementation of each method is as follows:

Import java. io. file; public class FileExercise {public static void main (String [] args) throws Exception {System. out. println ("the name Separator of the current operating system is:" + java. io. file. separator); System. out. println ("The path Separator of the current operating system is:" + java. io. file. pathSeparator); // String type File name String fileName = "daxiang.txt"; // instantiate the file object File = new File ("src", fileName ); file file1 = new File ("D: \ daxiang \ testjava \ src \ txt"); File file2 = new Fil E ("D :\\ daxiang \ testjava \ src"); // create a file. createNewFile (); // when fileis abstract, A daxiang.txt file boolean B will be created under the SRC folder of the current Java project; // declare a boolean variable // test whether the application can execute the file B = file. canExecute (); System. out. println ("test whether the application can execute the file" + B); // test whether the application can read the file B = file. canRead (); System. out. println ("test application can read this file" + B); // test whether the application can modify the file B = file. canWrite (); System. out. println ("test application can modify this file" + B); // test the text represented by this abstract path name. Whether the file or directory exists. B = file. exists (); System. out. println ("test whether the file or directory represented by this abstract path name exists" + B); // compare two abstract path names in alphabetical order: int I = file. compareTo (file1); // compareTo method, returns the ASCII code difference between the two strings before and after the comparison System. out. println (I); String path; // returns the absolute path name String of this abstract path name. path = file. getAbsolutePath (); System. out. println (path); // return the standard path name string of this abstract path name. path = file. getCanonicalPath (); System. out. println (path); long free; // returns the number of unallocated bytes in the partition specified by this abstract path. free = file. getFreeSpace (); Syst Em. out. println ("the number of unallocated bytes in the partition specified by this abstract path name" + free); // return the name of the file or directory represented by this abstract path name String name; name = file. getName (); System. out. println (name); name = file1.getName (); System. out. println (name); // returns the path string of the abstract path name parent directory. If this path name does not specify the parent directory, nullString parentpath; parentpath = file is returned. getParent (); System. out. println (parentpath); parentpath = file1.getParent (); System. out. println (parentpath); // returns the number of bytes that can be used on the virtual machine in the partition specified by this abstract path. free = file. GetUsableSpace (); System. out. println ("the number of bytes that can be used for this virtual machine in the partition specified by this abstract path name" + free); // calculate the hash code I = file for this abstract path name. hashCode (); System. out. println (I); // test whether the abstract path is an absolute path B = file. isAbsolute (); System. out. println ("Whether the abstract path name of the file object is an absolute path name:" + B); B = file1.isAbsolute (); System. out. println ("Whether the abstract path name of the file1 object is an absolute path name:" + B); // return the last modification time of the file represented by this abstract path name long time = file. lastModified (); System. out. println (time); // return the length of the object represented by the abstract path name long leng Th = file. length (); System. out. println ("file length:" + length); System. out. println (); // note the difference between list () and listFile () // list () --> Returns a string array, these strings specify the files and directories in the directory represented by this abstract path name: String [] array1 = file2.list (); for (I = 0; I <array1.length; I ++) {System. out. println (array1 [I]);} System. out. println (); // listFiles () --> returns an array of abstract path names, which indicate the files in the directory represented by this abstract path name [] array2 = file2.listFiles (); for (I = 0; I <array2.length; I ++) {System. o Ut. println (array2 [I]);} System. out. println (); // listRoots () --> list available File system root, static method File [] roots = File. listRoots (); for (I = 0; I <roots. length; I ++) {System. out. println (roots [I]);} System. out. println (); // request to delete the file or directory represented by this abstract path name when the VM ends. // File. deleteOnExit (); // create the file1.mkdir () directory specified by this abstract path name (); // rename the File file4 = new File ("src \ rename File"); System. out. println (file1.renameTo (file4); // sets the file Read-Only file. setReadOnly (); // sets the file to be writable. setWritable (true );}}

Iii. Examples of common File operations

<Span style = "font-size: 14px;">/*** instance operation 1: Create a new file * Create a test.txt file on the D Drive */import java. io. file; import java. io. IOException; public class FileOperate {public static void main (String [] args) {File f = new File ("d:" + File. separator + "test.txt"); // to increase portability, File is recommended. separatortry {f. createNewFile ();} catch (IOException e) {e. printStackTrace () ;}}/ *** instance operation 2: delete a specified file * Delete the test.txt file just created on the D Drive */import java. io. F Ile; public class FileOperate {public static void main (String [] args) {File f = new File ("d:" + File. separator + "test.txt"); if (f. exists () {// determine whether the file does not exist. If the file does not exist, you do not need to delete f. delete () ;}}/*** instance operation 3: Create and delete a file in combination *. Specify a path. If the file exists, delete it. If the file does not exist, create */import java. io. file; import java. io. IOException; public class FileOperate {public static void main (String [] args) {File f = new File ("d:" + File. separator + "test.txt" ); If (f. exists () {f. delete ();} else {try {f. createNewFile ();} catch (IOException e) {e. printStackTrace () ;}}}/*** instance operation 4: Create a folder * use mkdir () to create a folder */import java. io. file; public class FileOperate {public static void main (String [] args) {File f = new File ("d:" + File. separator + "test"); f. mkdir (); // create a folder}/*** instance operation 5: list all the files in the specified directory * If a directory is provided, you can directly list the contents in the directory. However, there are two methods listed in the File class: * returned in the form of a String array: public String [] list () * returned in the form of a File array: public File [] listFiles () * // *** instance operation 5: list all files in the specified directory * operation 1: Use list () list all content * This method lists the folders and file names in drive D */import java. io. file; public class FileOperate {public static void main (String [] args) {File f = new File ("d:" + File. separator); String [] str = f. list (); for (String s: str) {System. out. println (s) ;}}/ *** instance operation 5: list all files in the specified directory * operation 2: Use lis TFiles () lists * Full paths listed */import java. io. file; public class FileOperate {public static void main (String [] args) {File f = new File ("d:" + File. separator); File [] files = f. listFiles (); for (File file: files) {System. out. println (file) ;}}/ *** instance operation 6: determines whether a given path is a directory * given path, and whether it is a directory */import java. io. file; public class FileOperate {public static void main (String [] args) {File f = new File ("d:" + File. separator ); If (f. isDirectory () {System. out. println (f. getPath () + "is a directory");} else {System. out. println (f. getPath () + "not a directory") ;}}/*** instance operation 7: list all contents of a specified directory (recursively) * If a directory is specified, all files in this directory must be listed, including files in subfolders */import java. io. file; public class FileOperate {public static void main (String [] args) {File f = new File ("d:" + File. separator); print (f);} public static void print (File f) {if (f! = Null) {if (f. isDirectory () {File [] files = f. listFiles (); if (files! = Null) {for (File file: files) {print (file) ;}} else {System. out. println (f) ;}}}/*** instance operation 8: list the path name of the disk * @ param public static File [] listRoots () * @ return this method returns an array indicating the root file objects of the available file system. If you cannot determine the root of the group, this method returns null. */Import java. io. file; public class FileDemo {public static void main (String [] args) {File [] paths; try {// returns pathnames for files and directorypaths = File. listRoots (); // for each pathname in pathname arrayfor (File path: paths) {// prints file and directory pathsSystem. out. println (path) ;}} catch (Exception e) {// if any error occurse. printStackTrace () ;}}/ *** instance operation 9: list files and folders on a disk * @ param pub Lic static File [] listRoots () * @ return this method returns an array indicating the root File objects of an available File system. If you cannot determine the root of the group, this method returns null. */Import java. io. file; public class FileDemo {public static void main (String [] args) {File [] files = File. listRoots (); for (File file: files) {System. out. println (file); if (file. length ()> 0) {String [] filenames = file. list (); for (String filename: filenames) {System. out. println (filename) ;}}}/*** instance operation 10: file filtering * @ param FilenameFilter class * @ return */import java. io. file; import java. io. filenameFilter; imp Ort java. io. IOException; public class FileDemo {public static void main (String [] args) throws IOException {File dir = new File ("d :\\ daxiang \ testjava "); file [] files = dir. listFiles (new FilenameFilter () {// get. use the listFiles (FilenameFilter filter) method to create a Filterpublic boolean accept (File dir, String name) {if (name! = Null &&"". equals ("") {// check whether the file name is. if (name. toLowerCase (). endsWith (". java ") {return true ;}} return false ;}); for (File file: files) {System. out. println (file) ;}}</span>

Iv. Differences between file. getPath () getAbsolutePath () getCanonicalPath ()

For more information, see getPath, getAbsolutePath, and getCanonicalPath of the File class.

Import java. io. file; import java. io. IOException; public class getFilePath {public static void main (String [] args) throws IOException {System. out. println ("------ the default relative path, the obtained path is different -----"); File f = new File (".. \ src \ file "); System. out. println (f. getPath (); System. out. println (f. getAbsolutePath (); System. out. println (f. getCanonicalPath (); System. out. println ("------ the default relative path, the obtained path is different -----"); File f2 = new File (". \ src \ file "); System. out. println (f2.getPath (); System. out. println (f2.getAbsolutePath (); System. out. println (f2.getCanonicalPath (); System. out. println ("------ default absolute path, get the same path -----"); File f3 = new File ("C: \ src \ file"); System. out. println (f3.getPath (); System. out. println (f3.getAbsolutePath (); System. out. println (f3.getCanonicalPath (); // The execution result is: // ------ the default relative path, and the obtained path is different -----//.. \ src \ file // C: \ workspace \ Tip \.. \ src \ file // C: \ workspace \ src \ file // ------ the default relative path. The obtained path is different -----//. \ src \ file // C: \ workspace \ Tip \. \ src \ file // C: \ workspace \ Tip \ src \ file // ------ by default, the absolute path is the same -----/C: \ src \ file/C: \ src \ file // C: \ src \ file /// comparison. // getPath () returns the path in the constructor without any processing. // getAbsolutePath () the returned result is user. dir + getPath (), that is, the execution path plus the path // getCanonicalPath () in the constructor method, returns the path that completely parses the symbol, that is, the full path }}

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.