Java file explanation

Source: Internet
Author: User

First, Introduction

The file class is an abstract representation of "files" and "directory names ." Therefore, in the Java language, the file class can represent both files and directories.

Although most classes defined by Java.io are streaming, the file class is not, and it does not specify how information is read from or stored to a file. File describes the properties of the files themselves, directly processing files and file systems, is the only operation related to the file itself.

The inheritance and implementation interface of 1.1 file

File inherits directly from object, implements the serializable interface and the comparable interface.

 Public class Implements Serializable, comparable<file>
    • The file class implements the Serializable interface, which means that the file object supports serialization operations.
    • The file class implements the comparable interface, which means that file objects can be compared between sizes, and file can be stored directly in an ordered collection (such as TreeSet, TreeMap).
The structure diagram is as follows: 1.2 File use note 1, to create a file class object to be aware of the first place we want to distinguish between two nouns: absolute path and relative path.Absolute Path: The complete path, for example: D:\MyCode\Java\FileDemorelative Path: It will be generated in the place where the code is located, for example: Res/jay.txt will be in the directory of your code Jay.txt file in addition, because the path name character or the abstract path name of the conversion is inherent in the system is dependent. For example, in UNIX systems, absolute pathname prefixes are always "/", whereas in Windows systems, absolute pathname prefixes are always "\". Workaround for Prefix: Example 1: In Windows, the D:\Program files in the Java program must be "\" converted to "/" or "\ \", for example: D:/program files or d:\\program files If you want to make the program cross-platform, because Linux is "/", and Windows is "\", we can use the file provided by the constant string file.separator, which can be automatically converted to "/" or "\ \" Depending on the platform of the system. Common methods for 1.3 file

1) Determine if the file or directory exists: exists ()

2) Determine if it is a directory: isdirectory ()

3) Determine whether it is a file: isfile ()

4) Determine if the file is readable: canRead ()

5) Determine if the file can be written: canWrite ()

6) Determine if the file is hidden: ishidden ()

7) Determine if the file path is an absolute path: isabsolute ()

8) Determine if the file path is the same: equals (): Returns True,false

compareTo (): equal, equal return 0, less than return negative, greater than return positive

9) Get the absolute path to the file: GetAbsolutePath ()

10) Get file name: getName ()

11) Get File Size: length ()

12) Gets the file last modified: lastmodified ()

13) Get the path to the file: getpath ()

14) Get the directory for the upper-level file of the file: getParent ()

15) Create a new file: createnewfile ()

16) Create a new directory: mkdir ()

17) Delete file or directory: Delete ()

18) Name of the modified file: Renameto (str)

19) Modify the file to read-only: setreadonly ()

20) Modification Last modified: setlastmodified (long time)

Ii. Source Code Analysis 2.1 member variables all member variables are as follows: Some of the more critical member variables are listed below
//The FileSystem object representing the platform ' s local file system.
//Get local file system
PrivateStaticFinalFileSystem fs = Defaultfilesystem.getfilesystem ();

//file path name
PrivateFinalString path;

//Mark file path is invalid
PrivatetransientPathstatus status = NULL;

//The length of this abstract pathname ' s prefix, or zero if it has no prefix.
PrivateFinal transientintPrefixlength;

/**
* The system-dependent default Name-separator character. This field is
* Initialized to contain the first character of the value of the system
* Property <code>file.separator</code>. On UNIX systems , the value of this
* field is <code> '/' </code>; on Microsoft Windows Systems it is <code> ' \ \ ' </code>.
     *
*/
PublicStaticFinalCharSeparatorchar = Fs.getseparator ();

//The system-dependent Path-separator character, represented as a string for convenience.
PublicStaticFinalString PathSeparator =""+ Pathseparatorchar;
1. How does the member variable FS get to the local file system? In WindowsPlatform, in the downloaded JDK, we found the Winntfilesystem file system
That LinuxIt? So, a Linux version of the JDK, unzip, find Rt.jar. Then in the Java/io directory, we found the Unixfilesystem class。 The truth!

In fact, depending on the platform, the installation of different versions of the JDK, according to the platform under the corresponding version of the JDK, loading the local file system.

The member variable of FS is resolved, then the member variable of Separatorchar is solved.

2.2 Constructors

1, first look at the overall as follows:

2, choose a more representative method to explain 1) File (String pathname)
 Public File (String pathname) {
if (pathname = = null) {
Throw New NullPointerException ();
}
this. Path = fs.normalize (pathname);
this. Prefixlength = Fs.prefixlength (this. path);
}
The construction method primarily initializes the path, prefixlength two member variables, where path is normalized by the normalize public method in Winntfilesystem. The benefits of normalization, such as

Public Static void Main (string[] args)
{
File File = new file ("D:/test.txt");
System.out.println (File.getpath ());
}

File:

 Public String GetPath () {
return path;
}
Output: D:\test.txt The main input is pathname = "d:/test.txt" but Path gets "D:\test.txt".
2) file (file parent, String child)
 PublicFile (file parent, String child) {
if(Child = = null) {
ThrowNewNullPointerException ();
}
if(Parent! = NULL) {
if(Parent.path.equals ("")) {
This. Path = Fs.resolve (Fs.getdefaultparent (),
Fs.normalize (child));
}Else{
This. Path = Fs.resolve (Parent.path,
Fs.normalize (child));
}
}Else{
This. Path = Fs.normalize (child);
}
This. Prefixlength = Fs.prefixlength ( This. path);
}
The purpose of this is to assign a value to the two member variable of path and prefixlength. Among them, Fs.resolve (parent.path,fs.normalize (Child)); The purpose is to stitch the parent and sub-path 2.3 creation action within a reasonable range
    • CreateNewFile
    • Createtempfile
    • Mkdir

1) createnewfile ()

Public boolean createnewfile () throws IOException {
///1, check if you have permission to manipulate the file
SecurityManager security = System.getsecuritymanager ();
if (Security! = null) security.checkwrite (path);


///2, check if file path is valid
if (Isinvalid ()) {
Throw New IOException ("Invalid file path");
}


//3, in Windows, call the Createfileexclusively method in Winntfilesystem, which is called the system's underlying method.
return fs.createfileexclusively (path);
}

2) mkdir ()
This method creates a directory for this abstract path name.
Public boolean mkdir () {
SecurityManager security = System.getsecuritymanager ();
if (Security! = NULL) {
Security.checkwrite (path);
}
if (Isinvalid ()) {
return false;
}
return fs.createdirectory (this);
}
2.4 Delete Operations
    • Delete
    • Deleteonexit
1) Delete ()

public  boolean Delete () {
    //1, permission check
    securitymanager security = System.getsecuritymanager ();
    if (Security! = null) {
         security.checkdelete (path);
   }



///2, check if file path is valid
if (Isinvalid ()) {
return false;
}

//3, call the system local Bottom Delete method,
//But before deletion, some cleanup was done, cache.clear ();p refixcache.clear ();
return fs.delete (this);
}

And Deleteonexit is generally used to delete temporary files. Note: the File.delete () or File.deleteonexit () method can only delete files or empty folders
2.5 Get File Action 1) getabsolutefile ()

Public File Getabsolutefile () {
String Abspath = GetAbsolutePath ();
return New File (Abspath, Fs.prefixlength (Abspath));
}
2) Getcanonicalfile ()

Public throws IOException {
String Canonpath = Getcanonicalpath ();
return New File (Canonpath, Fs.prefixlength (Canonpath));
}
2.6 Get path Operation 1) GetAbsolutePath ()
This method returns the absolute path name string for this abstract pathname.
Public String GetAbsolutePath () {
return fs.resolve (this);
}
2) Getcanonicalpath ()
This method returns the canonical path name string for this abstract pathname.
Public throws IOException {
if (Isinvalid ()) {
Throw New IOException ("Invalid file path");
}
return fs.canonicalize (fs.resolve (this));
}
3) GetPath ()
This method converts this abstract path name to a pathname string.
Converts this abstract pathname into a pathname string
Here pathname is consistent with pathname in file (String pathname)
Public String GetPath () {
return path;
}
4) GetParent ()
//This method returns a string of the parent pathname of this abstract pathname, or null if the path name does not specify a parent directory. 
PublicString getParent () {
//Find the location of the last separator
intindex = Path.lastindexof (Separatorchar);
if(Index < Prefixlength) {
if((Prefixlength > 0) && (path.length () > Prefixlength))
returnPath.substring (0, prefixlength);
returnNull
}
//Get all characters before the last delimiter
returnPath.substring (0, index);
}
Because the source code in the file basically calls the system's underlying API, it is no longer introduced.

Reference: 1, Java IO Series 08 File summary 2, J2SE Knowledge points inductive notes (vii)---Java IO part 1:file class and Randomaccessfile class

3, illustrated Java IO: A, File source code

Java file explanation

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.