Java foundation of File

Disclaimer: This article is a blogger original article, please indicate the source: https://blog.csdn.net/qq_38182125/article/details/90610585

I. Overview

File class in the daily development should be a lot to see, as long as it relates to read and write files, often need the help of the File class. This article is the author of the study notes, use the File class will do a brief introduction, something like this:

  • What is File
  • File constructor
  • File common method
  • A simple example of File

Then we carry out a more detailed description of the File class above enumerated according to a summary of the content.


Second, what is File

File class is java.io package only represents the object disk file itself. File class defines a number of platform-independent methods to manipulate files to manipulate files through the File class method call is performed to create, delete, rename files and other operations. Object File class is mainly used to get some information about the file itself, such as the directory where the file length of the file, read and write file permissions and so on. Moreover File class has the following note:

  • In addition to the File object represents a file itself, but also represents a file directory;
  • File object is not the document itself, it actually represents a practical and file links is an abstract form of expression, this link is maintained by a virtual machine;
  • Seen from the second point, File objects that the referenced document is not necessarily real, it may be empty.

After a general understanding of the role of the File class, then we will start from the constructor, to understand how to use the File class.


Third, the File class constructor

File class has the following four construction method, the constructor, and meaning of the parameters in the following table:

method Explanation
File(String pathname) To create a new File instance by abstract pathname given pathname string conversion.
File(String parent, String child) Creates a new File instance from a parent pathname string and a child pathname string.
File(File parent, String child) Creates a new File instance from a parent abstract pathname and a child pathname string.
File (URI uri) By the given file: URI transformation to create a new File instance abstract pathname.

Then we pass under their respective use several examples to understand.

File(String pathname)

We assume for the location of the files C:\Users\Marck\Desktop\demo.jpg. This is a picture of the author on the desktop, we need to create a File instance to represent this image file, the code is as follows:

public class FileDemo {
    public static void main(String[] args) {
        String path = "C:\\Users\\Marck\\Desktop\\demo.jpg";
        // 构建File对象
        File file = new File(path);
    }
}

It should be noted that the characters '\'need to use the escape character '\\'to represent.

Then we think about a problem: The above file path C:\Users\Marck\Desktop\demo.jpgis the path of the Windows system representation, but on other operating systems may not be the path separator on '\'the. So is there any way to represent a unified path separators under different platforms it?

The answer is to use symbols '/'or call File.separator. The above-described image file path separator using the '/'following shall be represented C:/Users/Marck/Desktop/demo.jpg, in this form are common on any platform; call File.separatorway can achieve the same effect, the route is expressed in this form:

"C:" + File.separator + "Users" + File.separator + "Marck" + File.separator + "Desktop" + File.separator + "2.JPG";

It can also achieve cross-platform universal effect, but in general we prefer to use '/'representation, because the call File.separatormode tend to be more troublesome.

File(String parent, String child)

Still image file path in the above C:\Users\Marck\Desktop\demo.jpgexample, will be C:\Users\Marck\Desktopas its parent path, the code is as follows:

public class FileDemo {
    public static void main(String[] args) {
        String parentPath = "C:/Users/Marck/Desktop";
        File file = new File(parentPath, "demo.jpg");
    }
}

Examples File first method to achieve the effect created by this method is consistent with structure.

File(File parent, String child)

In fact, this construction method and use the second constructor is very similar, except that the first parameter type is File parent, still above the path of the image files, for example to create a picture file File object:

public class FileDemo {
    public static void main(String[] args) {
        File file = new File(new File("C:/Users/Marck/Desktop"), "demo.jpg");
    }
}

File instance and the second method to achieve the effect created by this construction method is the same.

File (URI uri)

This method of construction should be the most infrequently used, and it needs the uniform resource identifier URI is configured to assist class File instance code as follows:

public class FileDemo01 {
    public static void main(String[] args) throws URISyntaxException {
        URI uri = new URI("file:/C:/Users/Marck/Desktop/demo.jpg");
        File file = new File("C:/Users/Marck/Desktop/demo.jpg");
    }
}

Since the URI has nothing to do with knowledge of the subject, so here only briefly, created out of the code above File instance is created out of the first three constructors example effect is the same.


Four, File common method

File method very much, just below a list of daily use higher frequencies several methods, other methods can be viewed in its own Java official document, a common method in the following table:

method Explanation
getName() Returns the File object represents the name of the file or directory.
getPath() Returns the File object pathname string.
getAbsoultPath() File object returns the absolute pathname string.
getParent() Returns the File object's parent pathname string, if the File object does not have a parent directory, then return null.
exists() File or directory File object represents a test of whether or not there.
isFile() Test whether the file File object represents a regular file.
isDirectory() Test whether the file is a directory File object represents.

On the table of these methods are relatively simple, there is not an example of the stroke. The only caveat is that getPaththe method, if constructed File instance path is relative, it getPathis the return of a relative path name, File instance path if the building is an absolute path, then the getPathreturn is an absolute pathname, the following code be verified :

public class FileDemo {
    public static void main(String[] args) {
        // 传入参数为相对路径
        File file = new File("demo.jpg");
        System.out.println(file.getPath());
        // 传入参数为绝对路径
        file = new File("C:/Users/Marck/Desktop/demp.jpg");
        System.out.println(file.getPath());
    }
}

Output:

demo.jpg
C:\Users\Marck\Desktop\demp.jpg

Consistent with the above, we are talking about the situation. Next, several methods see include files are used to include files in the directory:

method Explanation
list() It returns an array of strings, naming the directory represented by the File object files and directories.
list(FilenameFilter filter) Returns a string array, the directory name represented by the File satisfy the specified filter object files and directories.
listFiles() Returns an array of File, it indicates that the file directory represented by the File object.
listFiles(FilenameFilter filter) File returns an array satisfy the specified filter named files and directories directory represented by the File object.
listRoots() Static methods of the File class, list the available file system root.

Next, using the above method will be explained by a few examples.

list()

Suppose we now want to list the name of the file on the desktop, the code is as follows:

public class FileDemo {
    public static void main(String[] args) {
        File file = new File("C:/Users/Marck/Desktop");
        String[] files = file.list();
        for (String s : files){
            System.out.println(s);
        }
    }
}

Results are as follows:

360 secure browser .lnk
Atom.lnk
Charles.lnk
the Cisco Packet Tracer.lnk
CodeBlocks.lnk
...

You can see the success print out all the files and directories in the current directory, if File instance represents a file object, listthe method returns null.

listFiles()

listFilesMethod and listis very similar, but listreturns an array of strings in the file name, and listFilesreturns the array is File, code as follows:

public class FileDemo {
    public static void main(String[] args) {
        File file = new File("C:/Users/Marck/Desktop");
        File[] files = file.listFiles();
        for (File f : files){
            System.out.println(f.getPath());
        }
    }

Run results are shown below:

C:\Users\Marck\Desktop\360安全浏览器.lnk
C:\Users\Marck\Desktop\Atom.lnk
C:\Users\Marck\Desktop\Charles.lnk
C:\Users\Marck\Desktop\Cisco Packet Tracer.lnk
C:\Users\Marck\Desktop\CodeBlocks.lnk

If the File object represents a file instead of a directory, it will also return null.

listRoots()

listRootsMethod returns the root of the file system, it is important to note that static methods of the File class, returns an array of File. Code as follows:

public class FileDemo {
    public static void main(String[] args) {
        File[] files = File.listRoots();
        for (File f : files){
            System.out.println(f.getPath());
        }
    }
}

Results are as follows:

C:\
D:\
E:\

I use a Windows system, so the system is returned three disk drive letter. If this code is running under Linux system, the results are as follows:

/

This is also consistent with our knowledge. Next we come to learn how to use File to create / delete files / folders.

method Explanation
mkdir() Create a directory named this File object. If the File object path contains a directory that does not exist, create failure.
mkdirs() Create a directory named this File object, including any necessary but nonexistent parent directories of.
createNewFile() If and only if a file with that name does not already exist, create a new empty file named this File object.
delete() Delete this File object represents a file or directory.

Next, using these methods to introduce by way of example.

mkdir & mkdirs

The only difference between the two methods are used to create the file directory path if the File object is a directory that does not exist, mkdircreate fails, and mkdirsthe method will create a non-existing directory. As an example: In C:/Users/Marck /Desktopthis path, we want to create a Tempdirectory, Tempthe directory still have to create a childsubdirectory, then it can be expressed as: C:/Users/Marck/Desktop/Temp/child. Note that at this time Tempdirectory and the childdirectory are non-existent.

We try mkdirto create a method for childthe directory, the code looks like this:

public class FileDemo {
    public static void main(String[] args) {
        File file = new File("C:/Users/Marck/Desktop/Temp/child");
        boolean flag = file.mkdir();
        System.out.println(flag);
    }
}

We use a booleanvariable flagto receive mkdirthe return value, print out the result value to determine whether to create a successful run the code, the following output:

false

It means creating childdirectory failed, in fact, the reason is very simple, childthe parent directory Tempis not yet exist, so the mkdirmethod can not create childdirectory. Therefore, mkdirways to create success must ensure that the parent directory in the directory are present in the case of appropriate use of mkdirsthe method, its benefits as long as the directory path does not exist it will be created, the code is as follows:

public class FileDemo {
    public static void main(String[] args) {
        File file = new File("C:/Users/Marck/Desktop/Temp/child");
        boolean flag = file.mkdirs();
        System.out.println(flag);
    }
}

Run results are shown below:

true

When we go to see on your desktop, you can also find it to create a Tempdirectory and its subdirectories child. In addition we have to realize is that whether mkdiror mkdirswhen the subdirectory already exists, will return directly false. Such as the above mkdirssample code to run again will find the printed result flase, and because the childdirectory already exists.

createNewFile()

createNewFileThe method used to create a new file (note not a directory), for example, we want to create a desktop 1.txttext file, the code is as follows:

public class FileDemo {
    public static void main(String[] args) throws IOException {
        File file = new File("C:/Users/Marck/Desktop/1.txt");
        boolean flag = file.createNewFile();
        System.out.println(flag);
    }
}

Run the code, the results are as follows:

true

When we go to see on the desktop you can also find really created a new empty text file 1.txt. Note that the createNewFilemethod throws IOExceptionan exception, and when the path is 1.txtwhen an existing file, the same will return false, meaning the file creation failed.

delete()

deleteThe method also can know from the name of the method is used to delete a file or directory, it deletes the file exists and success in return true, otherwise, they would return to falsethe example shown below:

public class FileDemo01 {
    public static void main(String[] args){
        File file = new File("C:/Users/Marck/Desktop/1.txt");
        boolean flag = file.delete();
        System.out.println(flag);
    }
}

Results are as follows:

true

Indicating successful deleted files 1.txt. If we once again run the above code, you will find returns false, because the 1.txtfile does not exist at this time.


Five, File simple example

Here we demonstrate a simple use File by two small examples.

1. list all files in the current directory name

By the previous example we know that list/listFilesthe method can include the file in the current directory, if you want to include all files in a directory, such as a file under the subdirectory, can be used to complete a recursive manner, the code is as follows:

public class FileDemo {
    public static void main(String[] args){
        File file = new File("C:/Users/Marck/Desktop");
        printFilename(file);
    }

    public static void printFilename(File file){
    	// 递归终止条件:file 为空或者不存在
        if (file == null || !file.exists()){
            return;
        }
        // 打印文件名
        System.out.println(file.getName());
        // 如果文件为目录,回调自身,继续打印
        if (file.isDirectory()){
            for (File f : file.listFiles()){
                printFilename(f);
            }
        }
    }
}

2. Calculate the size of the file

File this question we need the help of length()the method, which is used to calculate the size of the file in bytes (byte). It is worth noting that if you call the File object that represents the method is a directory, then its return value is zero. So we also need to traverse all the files in that directory, the statistics of the size of all files to return the added code is as follows:

public class FileDemo {

    public static int totalLength = 0;

    public static void main(String[] args){
        File file = new File("C:/Users/Marck/Desktop/简历管理");
        countLength(file);
        System.out.println(totalLength);
    }

    public static void countLength(File file){
        if (file == null || !file.exists()){
            return;
        }
        if (file.isFile()){
            totalLength += file.length();
        } else {
            for (File f : file.listFiles()){
                countLength(f);
            }
        }
    }


}

Here uses a static variable assist in the calculation, you can see countLengththe thinking and ideas actually the first question is no different, and better ways to discover the concrete by you. For example, recursive loop manner so as to avoid the situation StackOverflow occurs.


I hope this article helpful to you ~

Guess you like

Origin blog.csdn.net/qq_38182125/article/details/90610585