Use of the "Java IO Stream" file class

Source: Internet
Author: User

Use of the file class

The file class in Java is in Java.io.File, and the Java.IO.File class represents files or directories .

The file class is used only to represent information (name, size, and so on) of files (directories) and cannot be used for access to file content.

Introduction of common API of File class

First create a Test folder and text file under my D drive, as shown in:

1. Create a File object

  We create a file object to get a catalog of tests, and the most common way to create a file object is to create it through the path to the files, which is file (String path) , There are three ways for the same path:

 1  /*    3  */ 4  file File1=new  file ("D:\\co De "); //  5  file File2=new  file ("D:/code"); //  6  File file3=new  File ("D:" +file.separator+ "code"); // file.separator the static member of the File, set the delimiter  

It can also be created through File (parent directory, subdirectory) , such as:

1 file file=new file ("D:/code", "new4"); // Create subdirectories from parent directory

Equivalent to

        File file=new file ("D:/code/new4");

2. Exists () determine if a file or directory exists

Add the following code under the above code to see if this directory exists:

1 System.out.println (File1.exists ()); 2 System.out.println (File2.exists ()); 3 System.out.println (file3.exists ());

Operation Result:

3.mkdir () and mkdirs () create a directory or multilevel directory

Now I want to create a new subdirectory under that directory, then you can pass the mkdir () method, the following:

1 file file4=new file ("D:/code/new1"); 2         if (! file4.exists ()) {3            file4.mkdir ();  You can also use Mkdirs ()4         }

Run it, look at the directory you just found, and discover that a new directory was created successfully:

So I want to create a multilevel directory? Can be done through the mkdirs () method.

1 file file5=new file ("d:/code/new2/new3"); // Create a multilevel catalog 2         if (! file5.exists ()) {3             file5.mkdirs ();   Note that this cannot be done with mkdir (), only with mkdirs ()4         }

After running, look at the directory you just found and find that you have successfully created a multilevel directory:

4.isDirectory () and isfile () determine if it is a directory or whether it is a file

1System.out.println ("File5 is directory:" +file5.isdirectory ());2System.out.println ("Fil5 is file:" +file5.isfile ());3File5.delete ();//Delete directory4System.out.println ("is directory after deleting file5:" +file5.isdirectory ());5File file6=NewFile ("D:/code/hysum.txt");//Create a file6System.out.println ("File6 is directory:" +file6.isdirectory ());7System.out.println ("File6 is file:" +file6.isfile ());8File6.delete ();//Deleting Files9System.out.println ("Whether the file was deleted after File6:" +file5.isfile ());

Operation Result:

Results Analysis:

The Isdirectory () and Isfile () methods return true only if the directory or file exists and the type matches , and all two conditions are returned false!

5.delete () Delete files or directories

6.createNewFile () Create a new file

In the example above, I deleted the Hysum.txt file, and here I'm going to create the file through the CreateNewFile () method.

1 if (! file6.exists ()) {  2             try  {  3                file6.createnewfile (); 4             Catch (IOException e) {  5                 // TODO auto-generated Catch block 6                 e.printstacktrace (); 7             }  8         }

After the run is complete, look at the directory and find that the file was created successfully:

Note: CreateNewFile () throws an IOException exception and can be caught or thrown with a try-catch statement!

The above methods are the simplest, so let's take a look at the commonly used file get get method.

1.getAbsolutePath () Gets the absolute path .

2.getName () Gets the file name, which is the current directory.

3.getParent () Gets the parent path ( the parent path at the time of Creation ).

4.getPath () gets the path when the file is constructed .

Let's look through the code to see how the above method works;

1File file=NewFile (".", "new4");//. Represents the current path, using a relative path to create a directory2         if(!file.exists ()) {3 File.mkdir ();4System.out.println ("GetName () gets the file or directory name:" +file.getname ());5System.out.println ("GetAbsolutePath () Get absolute path:" +File.getabsolutepath ());6System.out.println ("GetParent () Gets the parent path:" +file.getparent ());7System.out.println ("GetPath () Get file directory:" +File.getpath ());8             9}

Operation Result:

Note:getParent () Gets the parent path that is created when the parent path is not the absolute path of the parent path, and the absolute path to get the parent path can go through file. GetParent (). GetAbsolutePath () to get.

-----------------different points ofGetPath () and GetAbsolutePath () -----------------------------

GetPath () Gets the path to the time the file was constructed .
GetAbsolutePath () Gets an absolute path . If the construction is the full path that directly returns the full path , if the construction time is a relative path, the path of the current directory is returned + the path to construct the file .

Second, use the file class to traverse the directory

Here are some simple ways to use the file class, which is a bit more complicated, we have to learn to traverse the directory through the file class, a series of operations on the directory.

Here I have created a new tool class for the file class named Fileutils. The function of this class is to list some common operations of file, such as filtering, traversing, and so on. Wrapping these operations into a tool class is a lot easier to do with the file object later using the tool class.

First select a test directory, just the D-Disk code directory, add a few text files inside.

---------------------------------FileUtils class method----------------------------------------

---------------lists all files under the specified directory (including its subdirectories) ---------------

There are two ways to list files in a directory: List () and Listfiles (), what is the difference between these two methods?

Let's look at the first method list (), which returns an array of type string

1  Public Static voidListDirectory (File dir)throwsioexception{2     if(!dir.exists ()) {//directory does not exist, throws an exception3         Throw NewIllegalArgumentException ("This directory does not exist");4     }5     if(!dir.isdirectory ()) {//not a directory6         Throw NewIllegalArgumentException ("Not a directory");7     }8String[] Filenames=dir.list ();//The list () method returns a string array9      for(String string:filenames) {Ten System.out.println (string); One     } A      -}

Main method Invocation Result:

Results analysis: You can see that list () returns the names of all the subdirectories and files that are directly under the directory, but does not contain the contents under subdirectories.

So how do you go through the files in the sub-directory?

If you want to iterate through the contents of the directory, you need to construct the file object to do the recursive operation, file provides the API to return the file object directly, that is the listfiles () method.

I have just modified the method as follows:

1  Public classFileUtils {2     /*3 * List all files under the specified directory (including their subdirectories)4      */5      Public Static voidListDirectory (File dir)throwsIOException {6         if(!dir.exists ()) {//directory does not exist, throws an exception7             Throw NewIllegalArgumentException ("This directory does not exist");8         }9         if(!dir.isdirectory ()) {//not a directoryTen             Throw NewIllegalArgumentException ("Not a directory"); One         } Afile[] Files =dir.listfiles (); -         if(Files! =NULL&& files.length > 0) {//To determine whether a subdirectory is included -              for(File file:files) { the                 if(File.isdirectory ()) {//if it is a subdirectory, do it recursively - listdirectory (file); -}Else{//if it is a file, the printout -System.out.println (file); +                 } -  +             } A         } at  -}

Operation Result:

You can see that the files are successfully traversed in all subdirectories and output.

-------------Summary ---------------

File.list () returns the name of the immediate subdirectory of the string array and does not contain content under subdirectories .

File.listfiles () Returns an object that is a direct subdirectory (file) .

Here are just a few common methods, more file class content please consult the API itself Oh ~

The file class is used only to represent files or directories and cannot be used for access to file contents;

The Randomaccessfile class provides access to the contents of the file, which can either read the file or write the file.

Next announcement "use of Randomaccessfile class"

Use of the "Java IO Stream" 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.