Java know how much (71) file and directory management

Source: Internet
Author: User
Tags java throws

A directory is a special mechanism for managing files, and keeping the same files in one directory simplifies file management and improves productivity. The Java language defines a file class in the Java.io package that is designed to manage disk files and directories.

Each file class object represents a disk file or directory whose object properties contain information about the file or directory. By invoking the various methods provided by the file class, you can create, delete, duplicate name files, determine read and write permissions for files, and whether they exist, set and query the last modified time of a file, and so on. Different operating systems have different ways of organizing file systems, and by using File class objects, Java programs can process files and directories in a platform-independent, unified manner.

To create an object of the File class

Creating a File class object requires a filename or directory name, as shown in table 10-9.

Table 10-9 How to construct the File class
Construction Method function Description
Public File (String path) Specifies the file or directory name associated with the file object, which can contain paths and file and directory names
Public File (string path, string name) Create a file object with the path as the name for the files or directory name
Public file (file dir, String name) Use the existing File object dir as the directory to create the file object with name as the filename or directory name
Public File (UR UI) To locate a file using the given Uniform Resource Locator


When using the constructor method of the File class, you need to be aware of the following points:
(1) The path parameter can be an absolute path, a relative path, or a directory on a disk.
(2) Because of different directory separators used by different operating systems, a static variable system.dirsep of the system class can be used to implement a common path under different operating systems. Such as:
"D:" +system.dirsep+ "Myjava" +system.dirsep+ "file"

Get Properties and actions

The file object enables you to obtain and manage and manipulate property information for files and related directories. Table 10-10 lists the methods and descriptions that are commonly used.

table 10-10 Common methods of File
Method function Description
Boolean CanRead () Returns true if the file is readable, otherwise returns false
Boolean canWrite () Returns true if the file is writable, otherwise returns false
Boolean exists () Determine if a file or directory exists
Boolean CreateNewFile () If the file does not exist, creates an empty file with the specified name and returns True if no return false exists
Boolean isfile () Determines whether an object represents a valid file
Boolean isdirectory () Determines whether an object represents a valid directory
Boolean Equals (File f) Compare whether two files or directories are the same
String GetName () A string that returns the file name or directory name
String GetPath () A string that returns the path to a file or directory
Long Length () Returns the number of bytes of the file, or 0 if the files object represents a directory
Long LastModified () Returns the time the file or directory was last modified
String[] List () Saves all file names in the directory in a string array and returns null if the file object is not a directory
Boolean Delete () Delete file or directory, must be empty directory to delete, delete successful return true, otherwise return false
Boolean mkdir () Creates subdirectories of the current directory, returns true successfully, or returns false
Boolean Renameto (File newFile) Renames a file to the specified file name


Example 10-11 determines whether an absolute path to an input represents a file or a directory. If the file outputs the absolute path to this file and determines the file attributes (whether read or write or hidden) of the file, the directory outputs all files in that directory (excluding hidden files).

1"Example 10-11"The absolute path of the input is to represent a file or a directory. If the file outputs the absolute path to this file and determines the file attributes (whether read or write or hidden) of the file, the directory outputs all files in that directory (excluding hidden files). 2 //********** Ep10_11.java **********3 ImportJava.io.*;4 classep10_11{5      Public Static voidMain (String args[])throwsioexception{6 String FilePath;7InputStreamReader in=NewInputStreamReader (system.in);8BufferedReader a=NewBufferedReader (in);9System.out.println ("Please enter an absolute path:");TenFilepath=a.readline ();//FilePath as the input value OneFile filename=NewFile (FilePath);//get the file name for this path A         if(Filename.isdirectory ()) {//determine if this file is a directory -System.out.println ((Filename.getname ()) + "for a directory"); -System.out.println ("================"); theFile Filelist[]=filename.listfiles ();//storing all files in the directory in an array -              for(inti=0;i<filelist.length;i++){ -                 if(Filelist[i].ishidden () = =false){//determine if the file is hidden -System.out.println (Filelist[i].getname ());//output non-hidden files +                 } -             } +         } A         Else{ atSystem.out.println ((Filename.getname ()) + "for a file"); -System.out.println ("================"); -             //get the file absolute path -SYSTEM.OUT.PRINTLN ("Absolute path is:" +Filename.getabsolutepath ()); -             //determine if this file can be read -System.out.println (Filename.canread ()? " Readable ": Non-readable"); in             //determine if this file can be modified -System.out.println (Filename.canwrite ()? " Modifiable ":" Cannot be modified "); to             //determine if this file is hidden +System.out.println (Filename.ishidden ()? " To hide file ":" Non-hidden file "); -         } the     } *}

Running result 10-11 shows:


Figure 10-11 Entering a file path after example 10_11 run result Series Articles:Java know how much (top)Java know how much (interface) interfaceJava knows how much (40) the difference between an interface and an abstract classJava know how much (41) generic explanationJava know how much (42) the range of generic wildcard characters and type parametersJava know how much (43) Exception Handling BasicsJava know how much (44) exception typeJava know how much (45) uncaught ExceptionsHow much Java knows (the) use of try and catchJava know how much (47) use of multiple catch statementsJava knows how much (in) the nesting of try statementsJava know how much (a) Throw: Exception throwsJava know how many () Java throws clausesJava knows how many (or) finallyJava know how much (52) built-in exceptionsJava know how much (53) Use Java to create your own exception subclassesJava know how much (54) assertion detailedJava know how many (55) threadsJava know how much (56) threading ModelJava know how much (57) main threadJava know how much (58) thread Runnable interface and thread class explanationJava know how much (59) Create multithreadingJava know how much (isAlive) and join () useJava know how much (61) thread PriorityJava know how much (62) thread synchronizationJava know how much (63) inter-thread communicationJava know how much (64) thread deadlockJava know how much (65) thread hangs, resumes, and terminatesJava know how much (66) Overview of input and output (IO) and streamsJava know how much (67) character-oriented input streamJava know how much (68) character-oriented output streamJava know how much (69) byte-oriented input and output streamJava know how much (70) application for byte stream

Java know how much (71) file and directory management

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.