Java_io flow _file class with use (where recursion is used)

Source: Internet
Author: User

First: The Java file class is very powerful, and Java can basically do all the work on the file. The following is a brief introduction to Java file Operations and common methods

Case 1: traverse the folder under the specified directory and output the file name

1 Static voidfinddirectory () {2         //building the file object, specifying the directory path (separator cross-platform delimiter)3File root =NewFile ("e://");//It is a string, because it is a path, all written in the format eg: "E://"and" E: "+file.separator functions the same4         //determine if this path exists (be sure to write this judgment, do not write, if not present will report NullPointerException exception)5         if(Root.exists ()) {6             //Remove all file and folder objects under the specified path7file[] Files =root.listfiles ();8              for(File file:files) {9                 if(File.isdirectory ()) {//if it is a folder (if not, the file will be output with the folder name)TenSystem.out.println ("folder name:" +file.getname ()); One                 } A             } -         } -}

The above method is simple explanation

1.boolean exists () Determine if files (files and folders) exist

2.boolean isdriectory () determine if a folder exists

3.String GetName () Gets the name of the file

Case 2://judgment E: Disk aa/under there is not a BB folder, if not, create it, if there is, create the file inside Tt.txt

1 Static voidCreateFile ()throwsioexception{2File file=NewFile ("E:/aa/bb/cc/tt.txt");3         //first determine if the file ancestor (BB) directory exists4         if(!File.getparentfile (). exists ()) {5             //Create a multilevel folder6 file.getparentfile (). Mkdirs ();7System.out.println ("Folder creation completed ...");8         }9         if(!file.exists ()) {Ten             //Create a file One file.createnewfile (); A         } -}

The relevant methods used in the above simple explanation

1.String getparentfile () If no parent directory returns null

2.boolean mkdir () Creating a directory

3.boolean mkdirs () Create a multilevel directory

4.boolean CreateNewFile () such as: E:/aa/tt.txt returns TRUE if the specified directory exists, or False if the TT file exists, but if no TT file exists, the TT file is created and then returns True

Case 3: traverse All files under the specified path (recursion is used)

1 Static voidoutfilename (String path) {2File rt=NewFile (path);3         if(!rt.exists ())4             return;5File[] Files=rt.listfiles ();6         if(files!=NULL&&files.length>0) {//This judgment is very important7              for(inti = 0; i < files.length; i++) {8                 if(Files[i].isfile ()) {9 System.out.println (Files[i].getname ());Ten}Else{ One                     //encountered a folder "pass this folder path to a method that queries files based on a path" A Outfilename (Files[i].getabsolutefile (). toString ());//The recursion is implemented here -                 } -             } the         } -}

The relevant methods used in the above simple explanation

1. File[] listFiles() 当路返回null有两种情况:第一,路径不存在;第二,路径存在,但没有访问权限

2. Long length()

Second: The combination application of IO stream _file class to realize the copying of files

classification of 1.IO streams

Divided into: character stream and byte stream according to different types of processing data

Divided into: input stream (InputStream) and output stream (OutputStream) based on data flow

The input stream can only be read, only write to the output stream

Eg: because the byte stream can handle all types of data (such as pictures, videos, etc.), here is a demo using the byte stream

Case 4: specify file, output file contents in console

1 Static voidOutfilecontext ()throwsexception{2File file=NewFile ("E:/ch01.txt");3         if(File.exists ()) {4             //building an input stream5InputStream in=Newfileinputstream (file);6             intSize=in.available ();7SYSTEM.OUT.PRINTLN ("File size:" +size);8             byte[] bytes=New byte[size];9 in.read (bytes);Ten in.close (); OneString str=NewString (bytes); ASystem.out.println ("Content:" +str); -         } -}

The relevant methods used in the above simple explanation

1.int available () estimated size of bytes returned for this file

2.intread(byte[] b) 从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b

Case 5: input stream + output stream +file class implements copy and dynamic movement of files

1 Static voidCopyFile ()throwsexception{2File file=NewFile ("E:/ch01.txt");3         if(File.exists ()) {4             //building an input stream5InputStream in=Newfileinputstream (file);6             //building an output stream7OutputStream out=NewFileOutputStream ("E:/newfile.txt");8             byte[] bytes=New byte[1024];9             intTemp=0;Ten              while((Temp=in.read (bytes))!=-1){ One out.write (bytes); A             } -Out.flush ();//Refresh the output stream cache -Out.close ();//turn off the output stream cache theIn.close ();//turn off input stream caching -         } -}

Note: line 10th, when read to the end of the file will return-1. Normally it will not return-1.

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

Summary: The file class +io flow in conjunction with the very common is the operation of files, so that the file can be added or deleted to change the copy movement and other operations are possible the above cases can only let you know some basic entry operations

Extension: The following is a common method of file

Judging method

1.boolean CanExecute () Determine if the file is executable

2.boolean canRead () Determine if the file is readable

3.boolean canWrite () Determine if the file is writable

4.boolean exists () determine if the file exists

5.boolean isdirectory ()

6.boolean Isfile ()

7.boolean Ishidden ()

8.boolean Isabsolute () determines whether an absolute path file does not exist or can be judged

Get method

1.String GetName ()

2.String GetPath ()

3.String GetAbsolutePath ()

4.String getParent ()//If no parent directory returns null

5.long lastmodified ()//Gets the last modified time

6.long Length ()

7.boolean Renameto (File f)

8.file[] Liseroots ()//Get Machine drive letter

9.string[] List ()

10.string[] List (filenamefilter filter)

Expansion: The following is a diagram of Io flow

IO flow is mainly used in hard-core, memory, keyboard and other processing equipment data operation, according to the data type of processing data can be divided into: byte stream (abstract base class is InputStream and OutputStream) and character stream (abstract base class for reader and writer).  Depending on the flow direction, it can be divided into: input stream and output stream. The main structure can be used to indicate:

End.....

"Success lies in Persistence"

Java_io flow _file class with use (where recursion is used)

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.