Java.io.File类在Java中的应用

来源:这里教程网 时间:2026-02-17 20:53:34 作者:

Java.io.File类在Java中的应用

File类是Java对文件或目录路径名的表示。因为文件和目录名在不同的平台上有不同的格式,一个简单的字符串不足以命名它们。文件类包含几个方法,用于处理路径名、删除和重命名文件、创建新目录、列出目录的内容,以及确定文件和目录的几个常见属性。

它是文件和目录路径名的一个抽象表示。一个路径名,无论是抽象的还是字符串形式的,都可以是绝对的或相对的。抽象路径名的父级可以通过调用该类的getParent()方法获得。首先,我们应该通过传递文件名或目录名来创建文件类对象。一个文件系统可以对实际文件系统对象的某些操作实现限制,如读、写和执行。这些限制被统称为访问权限。文件类的实例是不可改变的;也就是说,一旦创建,文件对象所代表的抽象路径名就不会改变。

如何创建一个文件对象

一个文件对象的创建是通过传入一个代表文件名称的字符串、一个字符串或另一个文件对象。比如说

File a = new File("/usr/local/bin/geeks");

这为/usr/local/bin目录下的geek文件定义了一个抽象的文件名。这是一个绝对的抽象文件名。

文件类的构造函数

File(File parent, String child): 从父级抽象路径名和子级路径名字符串中创建一个新的文件实例。File(String pathname): 通过将给定的路径名字符串转换为抽象路径名,创建一个新的文件实例。File(String parent, String child): 从一个父路径名字符串和一个子路径名字符串创建一个新的文件实例。File(URI uri): 通过将给定的文件转换为抽象路径名,创建一个新的文件实例。URI转换成一个抽象的路径名,从而创建一个新的文件实例。

文件类的方法

S. No.MethodDescriptionReturn Type
1.canExecute()测试应用程序是否可以执行这个抽象路径名所表示的文件。boolean
2.CanRead()测试应用程序是否可以读取这个抽象路径名表示的文件。boolean
3.CanWrite()测试应用程序是否可以修改这个抽象路径名表示的文件。boolean
4.compareTo(File pathname)按字母顺序比较两个抽象路径名。int
5.createNewFile()原子化地创建一个新的、以这个抽象路径名命名的空文件。boolean
6.createTempFile(String prefix, String suffix)在默认的临时文件目录下创建一个空文件。文件
7.delete()删除由这个抽象路径名表示的文件或目录。boolean
8.equals(Object obj)测试此抽象路径名与给定对象是否相等。oolean
9.exists()测试这个抽象路径名表示的文件或目录是否存在。布尔型
10.getAbsolutePath()返回这个抽象路径名的绝对路径名字符串。字符串
11.list()返回命名该目录中的文件和目录的字符串数组。字符串[]。
12.getFreeSpace()返回分区中未分配的字节数。long
13.getName()返回由这个抽象路径名表示的文件或目录的名称。字符串
14.getParent()返回这个抽象路径名的父路径名字符串。字符串
15.getParentFile()返回这个抽象路径名的父级的抽象路径名。文件
16.getPath()将这个抽象的路径名转换为路径名字符串。字符串
17.setReadOnly()标记命名的文件或目录,以便只允许读操作。boolean
18.isDirectory()测试这个路径名表示的文件是否是一个目录。布尔型
19.isFile()测试这个抽象路径名表示的文件是否是一个普通的文件。boolean
20.isHidden()测试这个抽象路径名表示的文件是否是隐藏文件。boolean
21.length()返回这个抽象路径名所代表的文件的长度。
22.listFiles()返回一个抽象路径名数组,表示目录中的文件。文件[]
23.mkdir()创建由这个抽象路径名命名的目录。boolean
24.renameTo(File dest)重命名由这个抽象路径名表示的文件。boolean
25.setExecutable(boolean executable)一个方便的方法来设置所有者的执行许可。boolean
26.setReadable(boolean readable)一个方便的方法来设置所有者的读取权限。boolean
27.setReadable(boolean readable, boolean ownerOnly)设置所有者或所有人的读取权限。boolean
28.setWritable(boolean writable)一个方便的方法来设置所有者的写权限。boolean
29.toString()返回这个抽象路径名的路径名字符串。字符串
30.toURI()构建一个代表此抽象路径名的文件URI。URI

例1: 检查一个文件或目录是否实际存在的程序。

// In this Java program, we accepts a file or directory name from// command line arguments. Then the program will check if// that file or directory physically exist or not and// it displays the property of that file or directory.  import java.io.File;  // Displaying file propertyclass fileProperty {    public static void main(String[] args)    {          // accept file name or directory name through        // command line args        String fname = args[0];          // pass the filename or directory name to File        // object        File f = new File(fname);          // apply File class methods on File object        System.out.println("File name :" + f.getName());        System.out.println("Path: " + f.getPath());        System.out.println("Absolute path:"                           + f.getAbsolutePath());        System.out.println("Parent:" + f.getParent());        System.out.println("Exists :" + f.exists());          if (f.exists()) {            System.out.println("Is writable:"                               + f.canWrite());            System.out.println("Is readable" + f.canRead());            System.out.println("Is a directory:"                               + f.isDirectory());            System.out.println("File Size in bytes "                               + f.length());        }    }}

输出

File name :file.txtPath: file.txtAbsolute path:C:\Users\akki\IdeaProjects\codewriting\src\file.txtParent:nullExists :trueIs writable:trueIs readabletrueIs a directory:falseFile Size in bytes 20

例2: 显示一个目录的所有内容的程序

这里我们将从键盘上接受一个目录名称,然后显示该目录的所有内容。为了这个目的,可以使用list()方法。

String arr[]=f.list();

在前面的语句中,list()方法使所有的目录条目被复制到数组 arr[]中。然后将这些数组元素arr[i]传递给File对象,并测试它们以了解它们是否代表一个文件或目录。

// Java Program to display all // the contents of a directoryimport java.io.BufferedReader;import java.io.File;import java.io.IOException;import java.io.InputStreamReader;  // Displaying the contents of a directoryclass Contents {    public static void main(String[] args)        throws IOException    {        // enter the path and dirname from keyboard        BufferedReader br = new BufferedReader(            new InputStreamReader(System.in));          System.out.println("Enter dirpath:");        String dirpath = br.readLine();        System.out.println("Enter the dirname");        String dname = br.readLine();          // create File object with dirpath and dname        File f = new File(dirpath, dname);          // if directory exists,then        if (f.exists()) {            // get the contents into arr[]            // now arr[i] represent either a File or            // Directory            String arr[] = f.list();              // find no. of entries in the directory            int n = arr.length;              // displaying the entries            for (int i = 0; i < n; i++) {                System.out.println(arr[i]);                // create File object with the entry and                // test if it is a file or directory                File f1 = new File(arr[i]);                if (f1.isFile())                    System.out.println(": is a file");                if (f1.isDirectory())                    System.out.println(": is a directory");            }            System.out.println(                "No of entries in this directory " + n);        }        else            System.out.println("Directory not found");    }}

输出

Enter dirpath:C:\Users\akki\IdeaProjects\Enter the dirnamecodewriting.idea: is a directoryan1.txt: is a filecodewriting.iml: is a filefile.txt: is a fileout: is a directorysrc: is a directorytext: is a fileNo of entries in this directory 7

相关推荐