Thinking logic for computer programs (59)-File and directory operations

Source: Internet
Author: User

In the first two sections we describe how to read and write the contents of a file through a stream, and this section describes some of the actions of file metadata and directories.

File and directory operations are ultimately related to the operating system and the file system, the implementation of different systems is not the same, but the Java Java.io.File class provides a unified interface, the underlying it will invoke the local method of the operating system and the specific implementation of the file system, this section, we introduce the file class.

The actions in the file class can be divided into three categories:

    • File meta data
    • File operations
    • Directory Operations

Before we introduce these operations, let's look at how file is constructed.

Construction method

File can represent both files and directories, and its main construction methods are:

 Public File (String pathname)  Public File (string parent, string child)  Public

Can be a parameter pathname that represents the full path, which can be a relative or absolute path. It can also be two parameters, which represents the parent of the parents Directory and the child that represents it.

The path in file can either already exist or it may not exist.

Creating a new file object from new does not actually create one, but creates an object that represents a file or directory, and the path in the files object is immutable after new.

File meta data

FileName and file path

With the file object, you can get its file name and path information, with the following methods:

 PublicString getName () Public BooleanIsabsolute () PublicString GetPath () PublicString GetAbsolutePath () PublicString Getcanonicalpath ()throwsIOException PublicString getParent () PublicFile getparentfile () PublicFile getabsolutefile () PublicFile Getcanonicalfile ()throwsIOException

GetName () returns the name of the file or directory, without the path name. Isabsolute () Determines whether the path in file is an absolute path.

GetPath () returns the full path name when constructing the file object, including the path and file name. GetAbsolutePath () returns the full absolute path name. Getcanonicalpath () returns the standard full pathname, which removes redundant names in the path, such as ".", "...", Tracking soft connections (Unix system concepts), and so on. These three paths are easy to confuse, let's look at an example to illustrate:

New File (".. /io/test/students.txt "); System.out.println (System.getproperty ("User.dir")); System.out.println ("path:" + F.getpath ()); System.out.println ("Absolutepath:" + F.getabsolutepath ()); System.out.println ("Canonicalpath:" + F.getcanonicalpath ());

Here, the file object is constructed using a relative path: Represents the previous level of the directory, the output is:

/users/majunchang/Iopath:.. /io/test//users/majunchang/io/. /io/test//users/majunchang/io/test/students.txt

The current directory for/users/majunchang/io,getpath () returns the relative path used when constructing the file object, while GetAbsolutePath () returns the full path, but contains the redundant path ". /io/", while Getcanonicalpath () removes the redundant path.

GetParent () returns the parent directory path, Getparentfile () returns the file object of the parent directory, and it is important to note that if the file object is a relative path, these methods may not get to the parent directory, such as:

New File ("Students.txt"); System.out.println (System.getproperty ("User.dir")); System.out.println ("Parent:" + f.getparent ()); System.out.println ("parentfile:" + f.getparentfile ());

The output is:

/users/majunchang/nullnull

Even if there is a parent directory, the return value of getParent () is null. So how do we solve this problem? You can first use the Getabsolutefile () or Getcanonicalfile () methods, which all return a new file object, with the new file object using GetAbsolutePath () and Getcanonicalpath () respectively The return value is constructed as a parameter. For example, modify the above code to read:

New File ("Students.txt"); System.out.println (System.getproperty ("User.dir")); System.out.println ("Parent:" + F.getcanonicalfile (). GetParent ()); System.out.println ("parentfile:" + f.getcanonicalfile (). Getparentfile ());

This time, we can get the parent directory, the output is:

/users/majunchang//users/majunchang//users/majunchang/io

There are four static variables in the file class that represent the path separators, which are:

 Public Static Final String Separator  Public Static Final Char Separatorchar  Public Static Final String PathSeparator  Public Static Final Char Pathseparatorchar

Separator and Separatorchar represent file path separators, which are generally "\" in Windows systems and generally "/" in Linux systems.

PathSeparator and Pathseparatorchar represent delimiters in multiple file paths, such as the delimiter in the environment variable path, the delimiter in the Java classpath variable classpath, and when the command is executed, The operating system looks for the command from the directory specified in path, and the Java runtime loads the class file, looking for the classpath from the path specified by Classpath. In a Windows system, this delimiter is generally '; ', and in a Linux system, this delimiter is generally ': '.

File basic information

In addition to the file name and path, the file object has the following methods to obtain basic information about the file or directory:

//whether the file or directory exists Public Booleanexists ()//is a directory Public Booleanisdirectory ()//is a file Public Booleanisfile ()//file length, number of bytes Public LongLength ()//last modified time, the number of milliseconds since the epoch Public Longlastmodified ()//Set the last modified time, set success to return True, otherwise return false Public BooleanSetlastmodified (LongTime

The return value of the length () method is meaningless for the directory.

It is necessary to note that the file object does not return the creation time method, because the creation time is not a public concept, Linux/unix does not have the concept of creation time.

Security and permissions Information

Security and permissions-related methods in the file class are:

//Is a hidden file Public BooleanIshidden ()//whether it can be executed Public BooleanCanExecute ()//whether it is readable Public BooleanCanRead ()//whether it can be written Public BooleanCanWrite ()//setting files as read-only files Public Booleansetreadonly ()//Modify file Read Permissions Public BooleanSetreadable (BooleanReadable,Booleanowneronly) Public BooleanSetreadable (Booleanreadable)//Modify File Write permissions Public BooleanSetwritable (BooleanWritable,Booleanowneronly) Public BooleanSetwritable (Booleanwritable)//Modify File executable permissions Public BooleanSetexecutable (BooleanExecutable,Booleanowneronly) Public BooleanSetexecutable (BooleanExecutable)

In the modification method, returns True if the modification succeeds, otherwise false. In the Set permissions method, Owneronly is true for owner only, false for all users, no method specified for Owneronly, owneronly equivalent to True.

File operations

File operations are primarily created, deleted, and renamed.

Create

Creating a new file object does not actually create files, but the following methods are available:

 Public Boolean throws

Create successfully returns TRUE, otherwise false, the newly created file content is empty. If the file already exists, it is not created.

The file object also has two static methods that can be used to create a temporary file:

 Public Static throws IOException  Public Static throws IOException

The full pathname of the temporary file is system-specified, unique, but can be specified by the parameter prefix (prefix), suffix (suffix), and directories (directory), prefix is required, and at least three characters, suffix if NULL, the default is ". tmp" , directory uses the system default directory if it is not specified or is specified as null. Let's look at an example:

File File = File.createtempfile ("Upload_", ". jpg"); System.out.println (File.getabsolutepath ());

Some of the running outputs on my computer are:

/var/folders/fs/8s4jdbj51jvcm7vc6lm_144r0000gn/t/upload_8850973909847443784.jpg

Delete

The file class deletes the following method:

 Public Boolean Delete ()  Public void deleteonexit ()

Delete Deletes the file or directory, returns true if the deletion succeeds, or returns false. If file is a directory and is not empty, delete will not succeed, return false, in other words, to delete the directory, first delete all subdirectories and files under the directory.

Deleteonexit adds the file object to the list to be deleted and deletes it when the Java virtual machine exits gracefully.

Renaming

The method is:

 Public Boolean

The parameter dest represents the renamed file, whether the rename succeeds with the system, or False if the success returns TRUE.

Directory Operations

When a file object represents a directory, you can perform directory-related operations, such as Create, traverse.

Create

There are two ways to create a table of contents:

 Public Boolean mkdir ()  Public boolean mkdirs ()

They are all created directories, the creation returns true successfully, and the failure returns false. It is important to note that if the directory already exists, the return value is false. The difference between the two methods is that if an intermediate parent directory does not exist, mkdir will fail, return false, and mkdirs will create the necessary intermediate parent directory.

Traverse

There are several ways to access subdirectories and files under a directory:

 Public string[] List ()  Public string[] List (filenamefilter filter)  Public file[] Listfiles ()  Public file[] Listfiles (filefilter filter)  Public File[] Listfiles (filenamefilter filter)

They return direct subdirectories or files and do not return files under subdirectories. The list returns an array of file names, and Listfiles returns an array of file objects. Both FilenameFilter and FileFilter are interfaces for filtering, and the filefilter is defined as:

 Public Interface filefilter {    boolean  Accept (File pathname);}

The filenamefilter is defined as:

 Public Interface filenamefilter {    boolean  Accept (File dir, String name);}

When traversing subdirectories and files, the Accept method of FilenameFilter or filefilter is called for each file, and only if the Accept method returns true will the subdirectory or file be included in the returned results.

The difference between FilenameFilter and FileFilter is that the FileFilter accept method parameter has only one file object, while the FilenameFilter accept method parameter has two, dir means the parent directory, Name indicates a subdirectory or file name.

Let's look at an example that lists all the files in the current directory that are suffixed with. txt, and the code can be:

New File ("."  = f.listfiles (new  filenamefilter () {    @Override    publicBoolean Accept (File dir, String name) {        if(Name.endswith (". txt"))            {return  true;        }         return false ;    }});  for (File file:files) {    System.out.println (File.getcanonicalpath ());}

We created an anonymous inner class object of FilenameFilter and passed it to listfiles.

Using the traversal method, we can easily perform recursive traversal to accomplish some more advanced functions.

For example, to calculate the size (including subdirectories) of all the files in a directory, the code can be:

 Public Static LongSizeofdirectory (FinalFile directory) {    LongSize = 0; if(Directory.isfile ()) {returndirectory.length (); } Else {         for(File file:directory.listFiles ()) {if(File.isfile ()) {size+=file.length (); } Else{size+=sizeofdirectory (file); }        }    }    returnsize;}

For example, in a directory, to find all files of the given file name, the code can be:

 Public StaticCollection<file> FindFile (FinalFile Directory,FinalString FileName) {List<File> files =NewArraylist<>();  for(File f:directory.listfiles ()) {if(F.isfile () &&f.getname (). Equals (FileName)        {Files.add (f); } Else if(F.isdirectory ()) {Files.addall (FindFile (f, fileName)); }    }    returnfiles;}

The Delete method of the file class is described earlier, we mentioned that if we want to delete the directory and the directory is not empty, we need to clear the directory first, using the traversal method, we can write a method to delete the non-empty directory, the code can be:

 Public Static voidDeleterecursively (FinalFile file)throwsIOException {if(File.isfile ()) {if(!File.delete ()) {            Throw NewIOException ("Failed to delete" +File.getcanonicalpath ()); }    } Else if(File.isdirectory ()) { for(File child:file.listFiles ()) {deleterecursively (child); }        if(!File.delete ()) {            Throw NewIOException ("Failed to delete" +File.getcanonicalpath ()); }    }}

Summary

This section describes how to use the file class to manipulate files and directories in Java, and the file class encapsulates the differences between the operating system and the file system, providing a unified API.

Understanding these operations, we go back and look at the operation of the contents of the file, the previous introduction is the flow, in addition to the flow, there are other ways of operation, such as random access and memory-mapped files, why do you need these methods? What are their characteristics? For what occasion? Let's move on to the next exploration.

----------------

To be continued, check out the latest articles, please pay attention to the public number "old Horse Programming" (Scan the QR code below), from the introduction to advanced, in layman's words, Lao Ma and you explore the nature of Java programming and computer technology. Original intentions, All rights reserved.

Thinking logic for computer programs (59)-File and directory operations

Related Article

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.