Java File class Detailed

In Java, the File class java.io package is the only object that represents a disk file itself, that is, if you want to manipulate files and directories in your program, it can be done through the File class. File class defines a number of ways to manipulate files, such as create, delete, rename files and directories.

File class can not access the contents of the file itself, if you need to access the contents of the file itself, you need to use input / output streams.

File class provides the following three forms of the constructor.

	File(String path):如果 path 是实际存在的路径,则该 File 对象表示的是目录;如果 path 是文件名,则该 File 对象表示的是文件。
	
	File(String path, String name):path 是路径名,name 是文件名。
	
	File(File dir, String name):dir 是路径对象,name 是文件名。

Using any of a constructor can create a File object, then call the method that provides the file operation.

File class common method

Method name Explanation
boolean canRead() Tests whether the application from the specified file for reading
boolean canWrite () Tests whether the application can write the current file
boolean delete() Specifies the file to delete the current
boolean exists() Test whether there is this File
String getAbsolutePath() Returns the file represented by this object is an absolute pathname
String getName() Returns the current file name or path name of the object (if it is a path, and finally a sub-path name is returned)
String getParent() Returns the File object corresponding to the current directory (the last one subdirectory) parent directory name
boolean isAbsolute() Test whether the current file File object represents an absolute pathname. This method eliminates the differences in different platforms, it can directly determine whether the file objects to an absolute path. On UNIX / Linux / BSD systems, if at the beginning of the pathname is a slash /, it indicates that the File object corresponds to an absolute path; on Windows systems, if the path begins with a drive letter, then it is an absolute path .
boolean isDirectory() Test whether the current file File object represents a path
boolean isFile() Test whether the current file File object represents a "normal" file
long lastModified() Returns the current file File object represents a time of last modification
long length() Returns the file length of the File object represents the current
String[] list() Returns a list of this File object specifies the path to the file
String[] list(FilenameFilter) File object returns a list of files specified in the current directory that satisfy the specified filter
boolean mkdir() Create a directory whose pathname is specified by this File object
boolean mkdirs() Create a directory whose pathname is specified by this File object
boolean renameTo(File) The current file is renamed File object specified for a given parameter File specifies the pathname

File class has the following two commonly used constants:

	public static final String pathSeparator:指的是分隔连续多个路径字符串的分隔符,Windows 下指;。例如 java -cp test.jar;abc.jar HelloWorld。
	
	public static final String separator:用来分隔同一个路径字符串中的目录的,Windows 下指/。例如 D:/Software/Common Files。

Note: You can see the naming constants defined in the File class does not meet the standard naming convention, constant name is not all upper case, because the development of Java after a considerable period of time, while naming convention is evolving, the File class appearance earlier, it did not have strict requirements on the naming convention, these are issues left over by history of Java.

	Windows 的路径分隔符使用反斜线“\”,而 Java 程序中的反斜线表示转义字符,所以如果需要在
	
	Windows 的路径下包括反斜线,则应该使用两条反斜线或直接使用斜线“/”也可以。Java 程序支持将斜线当成平台无关的路径分隔符。

Suppose you have a file in the Windows operating system D: \ javaspace \ hello.java, when used in Java, along the lines of the path should be D: /javaspace/hello.java or D: \ javaspace \ hello.java.

Get the file attributes

The first step in acquiring file attribute information in Java is to create a File class object and point to an existing file, and then call the method in Table 1 is operated.

There is a file located in the C: \ windows \ notepad.exe. Write Java programs to acquire and display the length of the file is writable, last modification date, and file attribute information paths. code show as below:

public class Test {
    public static void main(String[] args) {
        String path = "C:/windows/"; // 指定文件所在的目录
        File f = new File(path, "notepad.exe"); // 建立File变量,并设定由f变量引用
        System.out.println("C:\\windows\\notepad.exe文件信息如下:");
        System.out.println("============================================");
        System.out.println("文件长度:" + f.length() + "字节");
        System.out.println("文件或者目录:" + (f.isFile() ? "是文件" : "不是文件"));
        System.out.println("文件或者目录:" + (f.isDirectory() ? "是目录" : "不是目录"));
        System.out.println("是否可读:" + (f.canRead() ? "可读取" : "不可读取"));
        System.out.println("是否可写:" + (f.canWrite() ? "可写入" : "不可写入"));
        System.out.println("是否隐藏:" + (f.isHidden() ? "是隐藏文件" : "不是隐藏文件"));
        System.out.println("最后修改日期:" + new Date(f.lastModified()));
        System.out.println("文件名称:" + f.getName());
        System.out.println("文件路径:" + f.getPath());
        System.out.println("绝对路径:" + f.getAbsolutePath());
    }
}

The first parameter in the code above File class constructor specifies the location of the file, as used herein, C: / as the actual path of the file; a second argument specifies the file name. File class object created is f, then f acquired by calling a corresponding method attribute, as shown in the final operating results.

C:\windows\notepad.exe文件信息如下:
============================================
文件长度:193536字节
文件或者目录:是文件
文件或者目录:不是目录
是否可读:可读取
是否可写:可写入
是否隐藏:不是隐藏文件
最后修改日期:Mon Dec 28 02:55:19 CST 2016
文件名称:notepad.exe
文件路径:C:\windows\notepad.exe
绝对路径:C:\windows\notepad.exe

Creating and deleting files

File type not only can get property information for known file, you can also create files in the specified path, and delete a file . Create a file needs to be called createNewFile () method, delete files you need to call delete () method. Whether creating or deleting files are usually first call exists () method to determine whether a file exists.

Created on the C drive a test.txt file, detects whether the file exists when the program starts, if it does not exist is created; if it exists delete it and then create.

Codes are as follows:

public class Test {
    public static void main(String[] args) throws IOException {
        File f = new File("C:\\test.txt"); // 创建指向文件的File对象
        if (f.exists()) // 判断文件是否存在
        {
            f.delete(); // 存在则先删除
        }
        f.createNewFile(); // 再创建
    }
}

After running the program can be found in the C disk has been created test.txt file. However, if a different operating system, the path delimiter is not the same, for example:

	Windows 中使用反斜杠\表示目录的分隔符。
	
	Linux 中使用正斜杠/表示目录的分隔符。

Well, since the Java program itself portability features, the best path at the time of writing can automatically use the local operating system in line with the requirements of the separators according to the operating system resides on, so as to achieve the purpose of portability. To achieve this function, you need to use two constants in the File class provides.

Code changes as follows:

public static void main(String[] args) throws IOException {
    String path = "C:" + File.separator + "test.txt"; // 拼凑出可以适应操作系统的路径
    File f = new File(path);
    if (f.exists()) // 判断文件是否存在
    {
        f.delete(); // 存在则先删除
    }
    f.createNewFile(); // 再创建
}

Running result of the program and the program preceding the same, but in this case the program can use any operating system.

note: In operation files must use File.separator representing the separator. In developing the program, often using a Windows development environment, because the Windows operating system to support more development tools, easy to use, but often directly deployed on Linux or other operating system when the program is released, so then if do not use File.separator, the program is run, there may be a problem.

Create and delete directories

File class in addition to the creation and deletion of files, you can also create and delete directories . Create a directory need to call mkdir () method to delete the directory you need to call delete () method. Whether creating or deleting directories can call exists () method to determine whether a directory exists.

Determine whether there is config directory under the root directory of C, if present, remove and then created. Codes are as follows:

public class Test {
    public static void main(String[] args) {
        String path = "C:/config/"; // 指定目录位置
        File f = new File(path); // 创建File对象
        if (f.exists()) {
            f.delete();
        }
        f.mkdir(); // 创建目录
    }
}

Directory traversal

Directory traversal can find files in the specified directory, or to display a list of all the files . List File class () method provides a directory traversal function, the following method has two overloads.
1. String [] list ()
method which returns a string that represents an array of all files in a directory and subdirectory names consisting of the File object, if the call is not a directory File object, null is returned.

prompt: Array list () method returns the name of the file includes only and does not include the path. But it does not guarantee the same strings in the resulting array will appear in a specific order, in particular, that they appear in alphabetical order.

2. String [] list (FilenameFilter filter
) function and the method of the same list () method, except that the array returned contains only the files and directories of the filter in line with filter, if the filter is null, then accept all names.

Through all the files and directories in the root directory of C, and displays the file or directory name, type and size. Using the list () method of the codes are as follows:

public class Test {
    public static void main(String[] args) {
        File f = new File("C:/"); // 建立File变量,并设定由f变量变数引用
        System.out.println("文件名称\t\t文件类型\t\t文件大小");
        System.out.println("===================================================");
        String fileList[] = f.list(); // 调用不带参数的list()方法
        for (int i = 0; i < fileList.length; i++) { // 遍历返回的字符数组
            System.out.print(fileList[i] + "\t\t");
            System.out.print((new File("C:/", fileList[i])).isFile() ? "文件" + "\t\t" : "文件夹" + "\t\t");
            System.out.println((new File("C:/", fileList[i])).length() + "字节");
        }
    }
}

Since the character array list () method returns contains only the file name, so in order to obtain the file type and size, it must be converted to a File object and then call its methods. Operating results are shown below in the examples:

文件名称  文件类型  文件大小
===================================================
$Recycle.Bin  文件夹  4056字节
Documents and Settings  文件夹  0字节
Download  文件夹  12976326字节
DRIVERS  文件夹  0字节
FibocomLog  文件夹  67842字节
Gateface  文件夹  0字节
GFPageCache  文件夹  0字节
hiberfil.sys  文件  3375026176字节
Intel  文件夹  6782234字节
KuGou  文件夹  0字节
logs  文件夹  0字节
msdia80.dll  文件  904704字节
MSOCache  文件夹  0字节
MyDownloads  文件夹  0字节
MyDrivers  文件夹  946882字节
news.template  文件  417字节
NVIDIA  文件夹  0字节
OneDriveTemp  文件夹  7834345字节
opt  文件夹  0字节
pagefile.sys  文件  644250944字节
PerfLogs  文件夹  0字节
Program Files  文件夹  12288字节
Program Files (x86)  文件夹  8192字节
ProgramData  文件夹  12588字节
QMDownload  文件夹  0字节
Recovery  文件夹  1289字节
swapfile.sys  文件  268435456字节
System Volume Information  文件夹  12288字节
Users  文件夹  4096字节
Windows  文件夹  16784字节

I want to list only some of the files in the directory, which you need to call with a list () method filter parameters. First create a file filter, the filter must implement java.io.FilenameFilter interface and allows the specified file type accept () method.

Allow SYS, filter and BAK TXT file format implementation code:

public class ImageFilter implements FilenameFilter {
    // 实现 FilenameFilter 接口
    @Override
    public boolean accept(File dir, String name) {
        // 指定允许的文件类型
        return name.endsWith(".sys") || name.endsWith(".txt") || name.endsWith(".bak");
    }
}

Filter name created for the code above ImageFilter, only the next name to the list () method to implement a filter file.

String fileList[] = f.list(new ImageFilter());

Run the program again, through the results as follows:

文件名称        文件类型        文件大小
===================================================
offline_FtnInfo.txt        文件        236字节
pagefile.sys        文件        84365940字节
发布了457 篇原创文章 · 获赞 94 · 访问量 1万+

Guess you like

Origin blog.csdn.net/weixin_45743799/article/details/104709205