📜  Java Java类

📅  最后修改于: 2022-05-13 01:55:44.427000             🧑  作者: Mango

Java Java类

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

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

如何创建文件对象?

File 对象是通过传入一个表示文件名、String 或另一个 File 对象的字符串来创建的。例如,

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

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

文件类的构造函数

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

方法 文件类

S. No.MethodDescriptionReturn Type
1.canExecute()Tests whether the application can execute the file denoted by this abstract pathname.boolean
2.canRead()Tests whether the application can read the file denoted by this abstract pathname.boolean
3.canWrite()Tests whether the application can modify the file denoted by this abstract pathname.boolean
4.compareTo(File pathname)Compares two abstract pathnames lexicographically.int
5.createNewFile()Atomically creates a new, empty file named by this abstract pathname.boolean
6.createTempFile(String prefix, String suffix)Creates an empty file in the default temporary-file directory.File
7.delete()Deletes the file or directory denoted by this abstract pathname.boolean
8.equals(Object obj)Tests this abstract pathname for equality with the given object.boolean
9.exists()Tests whether the file or directory denoted by this abstract pathname exists.boolean
10.getAbsolutePath() Returns the absolute pathname string of this abstract pathname.String
11.list()Returns an array of strings naming the files and directories in the directory.String[]
12.getFreeSpace()Returns the number of unallocated bytes in the partition.long
13.getName()Returns the name of the file or directory denoted by this abstract pathname.String
14.getParent()Returns the pathname string of this abstract pathname’s parent.String
15.getParentFile()Returns the abstract pathname of this abstract pathname’s parent.File
16.getPath()Converts this abstract pathname into a pathname string.String
17.setReadOnly()Marks the file or directory named so that only read operations are allowed.boolean
18.isDirectory()Tests whether the file denoted by this pathname is a directory.boolean
19.isFile()Tests whether the file denoted by this abstract pathname is a normal file.boolean
20.isHidden()Tests whether the file named by this abstract pathname is a hidden file.boolean
21.length()Returns the length of the file denoted by this abstract pathname.long
22.listFiles()Returns an array of abstract pathnames denoting the files in the directory.File[]
23.mkdir()Creates the directory named by this abstract pathname.boolean
24.renameTo(File dest)Renames the file denoted by this abstract pathname.boolean
25.setExecutable(boolean executable)A convenience method to set the owner’s execute permission.boolean
26.setReadable(boolean readable)A convenience method to set the owner’s read permission.boolean
27.setReadable(boolean readable, boolean ownerOnly)Sets the owner’s or everybody’s read permission.boolean
28.setWritable(boolean writable)A convenience method to set the owner’s write permission.boolean
29.toString()Returns the pathname string of this abstract pathname.String
30.toURI()Constructs a file URI that represents this abstract pathname.URI

示例 1:检查文件或目录是否物理存在的程序。

Java
// 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 property
class 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());
        }
    }
}


Java
// Java Program to display all 
// the contents of a directory
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
  
// Displaying the contents of a directory
class 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");
    }
}


输出:

File name :file.txt
Path: file.txt
Absolute path:C:\Users\akki\IdeaProjects\codewriting\src\file.txt
Parent:null
Exists :true
Is writable:true
Is readabletrue
Is a directory:false
File Size in bytes 20

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

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

String arr[]=f.list();

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

Java

// Java Program to display all 
// the contents of a directory
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
  
// Displaying the contents of a directory
class 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 dirname
codewriting
.idea
: is a directory
an1.txt
: is a file
codewriting.iml
: is a file
file.txt
: is a file
out
: is a directory
src
: is a directory
text
: is a file
No of entries in this directory 7

相关文章: Java中的 FileReader 和 FileWriter