JAVA 52nd-IO stream (6) File object

Source: Internet
Author: User

JAVA 52nd-IO stream (6) File object

File class

Used to encapsulate files or folders as objects.

Convenient operations on file and folder attributes

The File object can be passed to the stream constructor as a parameter.

1. constructor and Separator

Public static void FileDemo () {// constructor demo // You can encapsulate an existing or nonexistent File or directory into a File object file File = new File ("d: \ a.txt "); File file2 = new File (" d: "," a.txt "); File file3 = new File (" d :\\"); file file4 = new File (file3, "a.txt"); File f = new File ("d: \ sd \ a.txt "); // different operating systems have different separators. In Windows, \ File f2 = new File ("d:" + File. separator + "sd" + File. separator + "a.txt"); // equivalent to the previous sentence, in all. the separator method is actually System. getProperty (....); system. out. println (f2 );}

Ii. Class Methods

1. Get

Get File Name: File. getName ()
Obtain the File path: File. getpath ()/getAbsolutePath ()
Get File size: File. length ()
Get File modification time: File. lastModified ()

Public static void FileMethodDemo () throws IOException {File file = new File ("A.txt"); String filename = file. getName (); // get the file name String absfilepath = file. getAbsolutePath (); // obtain the absolute path String path = file. getPath (); // obtain the relative path long len = file. length (); // file size long time = file. lastModified (); // last modification time Date date = new Date (time); DateFormat df = DateFormat. getDateTimeInstance (DateFormat. LONG, DateFormat. LONG); String time1 = df. format (date); String parent = file. getParent (); // obtain the parent directory System. out. println ("name:" + filename); System. out. println ("abspath:" + absfilepath); System. out. println ("path:" + path); // new File ("xxx"), what is xxx? System. out. println ("filelen:" + len); System. out. println ("filetime:" + time1); System. out. println ("filepatent:" + parent );}

2. Create and delete

Public static void FileMethodDemo () throws IOException {// create and delete a File // create a file File = new file ("file.txt"); boolean falg = File. createNewFile (); System. out. println ("flag:" + falg); // unlike the output stream, it is created if it does not exist. Otherwise, it is not created. // boolean flag1 = file is deleted. delete (); // boolean falg = file. deleteOnExit (); when exiting, delete System. out. println ("remove flag:" + flag1); // create and delete folders // create a single-level directory File dir = new File ("ACM"); boolean B = dir. mkdir (); // create a single-level directory System. out. println ("B:" + B); // Delete dir. delete (); // note the following in the Window, the contents in the folder cannot be deleted. // The multilevel directory File dir = new File ("ACM \ asd \ as \ ad"); dir. mkdirs (); // create a multi-level directory System. out. println (dir. delete (); // only ad is deleted, and other files are parent directories }}


PS: if the file is being operated by a stream, it cannot be deleted.
3. Judgment

Public static void FileMethodDemo () throws IOException {// judge File file = new File ("A.txt"); boolean flag = file. exists (); // whether the specified a.txt contains boolean flag1 = file. isFile (); // determines whether it is a file boolean flag2 = file. isDirectory (); // determines whether the directory is System. out. println (flag + ":" + flag1 + ":" + flag2 );}

4. Rename and cut

Public static void FileMethodDemo () throws IOException {//// rename // File file = new File ("D: \ .mp3 "); // File file2 = new File ("D: \ __1.mp3"); // file. renameTo (file2); // rename/cut File file = new File ("D: \ _1.mp3") in the same directory; File file2 = new File ("G: \ happy summer "); file. renameTo (file2); // cut in different directories}

5. Get the directory content

Public static void FileMethodDemo () throws IOException {File file = new File ("c: \"); // File ("c: \ a.txt "); if it is not a directory but a File, a null pointer exception occurs, and the array is not created successfully. // if the system-level directory is accessed, a null pointer exception occurs. // File ("c: \ eqwwrfg ") if the directory exists and NO content exists, an array is returned, but the length is 0 // get the name of the file and folder in the current directory and the hidden file String [] str = file. list (); for (String p: str) {System. out. println (p );}}

Filter:

If the. java file in drive C is used, the filter is used.

list(FilenameFilter filter)
Returns an array of strings that specify the files and directories that meet the specified filter in the directory indicated by this abstract path name.

FilenameFilter,The class instance that implements this interface can be used for the filter file name.

This interface has only one method:

accept(File dir,String name)
Test whether the specified file should be included in a file list. : Returned only when the name should be included in the file listtrueOtherwisefalse.

Import java. io. *; class FilerJava implements FilenameFilter {public boolean accept (File dir, String name) {// System. out. println (dir + "----" + name); return name. endsWith (". java "); // file suffix} public class Main {public static void main (String [] args) throws IOException {FileMethodDemo ();} public static void FileMethodDemo () throws IOException {File file = new File ("c: \"); String [] str = file. list (new FilerJava (); for (String p: str) {System. out. println (p );}}}

In fact, the filter first traverses all the files in one directory. If the conditions are met, true is returned.


listFiles(FileFilter filter)
Returns an array of abstract path names, which indicate the files and directories that meet the specified filter conditions in the directories indicated by this abstract path name.

Import java. io. *; class FilerHidden implements FileFilter {@ Overridepublic boolean accept (File pathname) {// TODO Auto-generated method stubreturn! Pathname. isHidden (); // display non-hidden objects} public class Main {public static void main (String [] args) throws IOException {FileMethodDemo ();} public static void FileMethodDemo () throws IOException {File dir = new File ("C: \"); File [] files = dir. listFiles (new FilerHidden (); // obtain all non-hidden objects in the current directory for (File f: files) {System. out. println (f );}}}

Simple Application of filters

import java.io.*;class FilerHidden implements FilenameFilter{private String houzhui;public FilerHidden(String houzhui) {super();this.houzhui = houzhui;}public boolean accept(File dir, String name) {return name.endsWith(houzhui);}}public class Main {public static void main(String[] args) throws IOException {FileMethodDemo();}public static void FileMethodDemo() throws IOException {File dir = new File("C:\\");File[] files = dir.listFiles(new FilerHidden(".java"));for(File f : files){System.out.println(f);}}}

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.