Java IO (i): File class

Source: Internet
Author: User
Tags file separator

Introduction to the 1.File class

The file class is located in the Java.io package. It operates at the file hierarchy level, viewing the file, while the byte stream and character stream manipulate the data more clearly than the underlying.

The learning file class includes the following key points: path, file delimiter, create file (directory), delete file (directory), view file contents (output directory file), Judge file (is file/directory?). Is there a no? Can read and write execute? ), get file information (file name, path name, size, and so on), and finally how to filter the required files .

2. Create and delete files/directories

The file class has four constructor methods: file (String pathname), file (string parent,string child), file (file parent,string child), file (Uri Uri), The last one is not considered.

new File("D:\\myjava\\a.txt");      //File(String pathname)File file2 = new File("D:\\myjava","a\\b.txt"); //File(String parent,String child)File file3 = new File(file2,"abc"); //File(File parent,String child)

New A file object indicates that a file instance has been created and does not represent the creation of the actual files in the file system. To create an actual file, directory, you should use the methods provided in the file class:

    • boolean createNewFile() throws IOException: Creates a new empty file that is created and returns true only if the file does not exist.
    • static createTempFile(): Creates a temporary file.
    • boolean mkdir(): Creates an empty directory that is created and returns true only if the parent path exists and the directory to be created does not exist. Note: Parent directories are not created recursively.
    • boolean mkdirs(): Unlike mkdir (), mkdirs () recursively creates all the required parent paths.

For example, creating a d:\myjava\a.txt,d:\myjava\a\abc\c.txt in D:\myjava (already exists) provides a way to do this.

 file file0 = new File ( "Xyz.txt")   ; //relative path, relative to the User.dir path in the system property, file File1 = new file ( "D:\\myjava\\a.txt"); File File2 = new File ( "D:\\myjava",  "A\\abc"); File File3 = new File (File2, "C.txt");  try {system. Out.println (File1.createnewfile ()); //try ... catch createnewfile () System. out.println (File2.mkdirs ()); System. out.println (File3.createnewfile ());} catch (IOException e) {e.printstacktrace ();       

Notice the double backslash above \\ because the file delimiter for the Windows system is \ , and this is the escape symbol, so you need to \ escape it. The file separator symbol is in the UNIX operating system / , but Windows is also able to use it correctly / as a delimiter.

The execution code returns true for the first time the file is created, but the second execution returns false because the file to be created already exists. As follows:

λ java TestCreatetruetruetrueλ java TestCreatefalsefalsefalse

The file class provides only a delete () method to delete files and directories, and only empty directories when deleting directories. Note: This is permanently deleted and does not enter the Recycle Bin.

System.out.println(file1.delete()); //trueSystem.out.println(file2.delete()); //falseFile file4 = new File("d:/myjava/a/abc/c.txt");System.out.println(file4.delete()); //true
File name and path-related issues

Each file object has a parent path, a file name, and the combination of the two is the absolute path to the document. In addition, the path is divided into relative paths (abstract paths), absolute paths.

In the case of Unix path naming,/etc/ssh is dirname in absolute path/etc/ssh/ssh_config, that is, parent path, Ssh_config is basename. Similarly in Windows, such as dirname in absolute path c:\windows\system32\drivers\etc\hosts is c:\windows\system32\drivers\etc, The basename section is the hosts.

The following are the methods provided by the file class that are related to file names, parent paths, and paths.

    • getName(): Gets the file name. Gets the abstract path name given in the file object, which is the basename part of the path.
    • getAbsoultePath(): Gets the absolute path name, which is dirname/basename.
    • getParent(): Gets the parent path, which is dirname.
    • getPath(): Gets the string for the file path, which is actually called ToString (). Relative or absolute paths may be returned. See below for explanations.
    • File getAbsoulteFile(): Gets the file object of the absolute path, and note that it returns files.
    • File getParentFile(): Gets the file object of the parent path, and note that it returns files.

At new file, you can give a relative path (relative to User.dir), or you can give an absolute path. For example, in the following 4 new file, except the first is a relative path, the remaining three are absolute paths.

new File("xyz.txt");     //相对路径,相对于system属性中的user.dir路径File file1 = new File("D:\\myjava\\a.txt");File file2 = new File("D:\\myjava","a\\abc");File file3 = new File(file2,"c.txt");

When a relative path is given, GetParent () and getparentfile () do not get to the parent path correctly, return null, and GetPath () returns the file name of the relative path, which is the path given by the new file (path). will return to what path. However, Getabsoultepath () is always able to get to the absolute path.

File FILE0 =New File ("1.txt"); File file1 =New File ("D:/myjava/a.txt"); File file2 =New File ("D:/myjava","A/abc"); File File3 =New File (File2,"C.txt"); System.Out.println ("----------FILE0-----------------"); System.Out.println (File0.getabsolutefile ());D:\myjava\io\1.txtSystem.Out.println (File0.getabsolutepath ());D:\myjava\io\1.txtSystem.Out.println (File0.getname ());1.txtSystem.Out.println (File0.getparent ());Nullsystem.Out.println (File0.getparentfile ());Nullsystem.Out.println (File0.getpath ());1.txtSystem.Out.println ("----------file1-----------------"); System.Out.println (File1.getabsolutefile ());D:\myjava\a.txtSystem.Out.println (File1.getabsolutepath ());D:\myjava\a.txtSystem.Out.println (File1.getname ());A.txtsystem.Out.println (File1.getparent ());D:\myjavaSystem.Out.println (File1.getparentfile ());D:\myjavaSystem.Out.println (File1.getpath ());D:\myjava\a.txtSystem.Out.println ("----------file2-----------------"); System.Out.println (File2.getabsolutefile ());D:\myjava\a\abcSystem.Out.println (File2.getabsolutepath ());D:\myjava\a\abcSystem.Out.println (File2.getname ());Abcsystem.Out.println (File2.getparent ());D:\myjava\aSystem.Out.println (File2.getparentfile ());D:\myjava\aSystem.Out.println (File2.getpath ());//d:\myjava\a\abcsystem. out.println ("----------file3-----------------"); System. out.println (File3.getabsolutefile ()); //d:\myjava\a\abc\c.txtsystem. out.println (File3.getabsolutepath ()); //d:\myjava\a\abc\c.txtsystem. out.println (File3.getname ()); //c.txtsystem. out.println (File3.getparent ()); //d:\myjava\a\abcsystem. out.println (File3.getparentfile ()); //d:\myjava\a\abcsystem. out.println (File3.getpath ()); //d:\myjava\a\abc\c.txt              
3. File evaluation and file attribute correlation

New file object, regardless of whether the object is a file or a directory, the new way is the same, that is, from the new file does not recognize whether the object is a file or directory, and can not confirm that the object corresponding to the existence of the file. In addition, the file is readable, writable, executable, etc. can also be judged. In fact, these are the attributes of the file, in addition to the information, the file name, size, last modified time, etc. are also file attributes.

    • exists(): Whether the file object exists in the filesystem.
    • isFile(): Whether the file object exists in the filesystem and is a normal file.
    • isDirectory(): Whether the file object exists in the filesystem and is a directory.
    • canRead(): Whether the file object is readable.
    • canWrite(): Whether the file object is writable.
    • canExecute(): Whether the file object can be executed.

There are also two ways to get common properties:

    • length(): File size, Unit bytes. Can be used to determine whether empty files, empty directories.
    • lastModified(): The last modification time, which is mtime.

You can also set properties such as read, write, execute, last modified time, and so on.

    • setLastModified(long time): Time is expressed as a number of milliseconds starting in 1970-01-01.
    • setExecutable(true/false): TRUE or False for all users to be able to execute
    • setExecutable(true/false,true/false): The second parameter represents owneronly, and True indicates that only the owner can do it, otherwise all users are executable.
    • setWritable(true/false): As with Setexecute (), the owneronly parameter is also supported.
    • setReadable(true/false): As with Setexecute (), the owneronly parameter is also supported.
    • setReadOnly(): Set read-only, setting success returns TRUE.
4. List the files in the directory

The file class does not provide a way to view the contents of the files, only provides a way to view the contents of the directory, that is, lists the list of files in the directory. These methods only list the contents of the current directory and do not recursively traverse through subdirectories.

    • String[] list(): Returns an array of strings whose elements are the basename of the files in this directory.
    • String[] list(FilenameFilter filter): Returns an array of strings whose elements are basename that satisfy the filtering criteria.
    • File[] listFiles(): Returns an abstract path to the an array group, an element of basename for the file in this directory.
    • File[] listFiles(FileFilter filter): Returns the abstract path an array group, which is the basename that satisfies the filter condition.
    • File[] listFiles(FilenameFilter filter): Returns the abstract path an array group, which is the baesname that satisfies the filter condition.

Because the file list returns multiple values, even multiple file objects, these method return values are in the form of an array. An array, not a collection, is because the number of elements in the array is immutable, and the list of files in the directory is the action of listing the files in the current moment of the directory, and if there is an increment or delete element, the list before is listed, and the other list is actually listed?

First look at the list () and listfiles () without the filter, the method for file filtering is described later. Suppose the structure in the D:\a directory is as follows:

d:\a|--a.sql|--back.log|--b| |--e|  | |--1.txt| | |--2.txt| | ' --3.txt| ' --f| |--4.txt| | --5.txt| ' --6.txt| --c| | --e| | | --ace1.txt| | | --ace2.txt| | ' --ace3.txt| ' --f| | --4.txt| | --5.txt| ' --6.txt ' --d |--a.java | --ABC (1). txt | --ABC (2). txt | --ABC (3). txt | --b.java ' --c.java        

Lists the list of files within the d:\a.

new File("d:/a");String[] list = file1.list();for (String f : list) { System.out.println(f);}

The results obtained are

a.sqlbback.logcd

The actual procedure is to store the file name in the directory in a string array, and then iterate over the array. Moreover, the result is only the basename part of the file name, not the absolute path. In fact, because it is stored in string[], there is absolutely no way to get its absolute path. Therefore, a better way is to use the Listfiles () method, because it returns a file array in which each element is a file object, and you can use GetAbsolutePath () to get the absolute path of each element.

new File("d:/a");File[] filelist = file1.listFiles();for (File file : filelist) {    System.out.println(file.getAbsolutePath());}

The results are as follows:

d:\a\a.sqld:\a\bd:\a\back.logd:\a\cd:\a\d

For a list of directories, here are a few examples, see: Java displays a list of directory files and deletes directories.
Example 1: Listing files in the entire directory (recursive)
Example 2: List files in the entire directory (queue)
Example 3: Tree structure displays files in the entire directory (recursive)
Example 4: Delete an entire directory

5. Filtering files

The file filtering feature is supported by Listfiles () of the Files class. For example File[] listFiles(FileFilter filter) , where FileFilter is the filter interface, you need to implement the interface to filter the files.

The common filtering method is based on the file name, in fact, also support other filter conditions, such as whether readable, size is greater than 5M, and so on.

Import java.io.*;PublicClassFilter1 {PublicStaticvoidMain(string[] args) {File dir =New File ("D:/myjava"); Getjavafiles (dir); }PublicStaticvoidGetjavafiles(File dir) {file[] files = dir.listfiles (New Namefilter ());for (File file:files) {if (File.isdirectory ()) {getjavafiles (file);}else {System.out.println (File.getabsolutepath ());}} }}Implementing the FileFilter InterfaceClassnamefilter implements FileFilter { Span class= "hljs-function" >public boolean accept (File pathname) {if ( Pathname.isdirectory ()) {//in order to support recursive filtering, determine the directory return true; } else {String name = Pathname.getname (); return name.endswith ( ". Class")?  True:FALSE; //return pathname.canread () True:false;//based on whether readable filtering //return Pathname.length () >5242880?true:false; Filter by size great than 5MB? (5*1024*1024)} }} 

Java IO (i): File class

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.