java file类_Java File类

java file类

In Java, File class is used for the representation of files or directory pathname. Because of the names of files and directory have different formats on a different platform. The path of a file can be absolute or relative. There are many methods of file classes which can be used for creating, reading, deleting or renaming a file.

在Java中,File类用于表示文件或目录路径名。 由于文件名和目录名在不同平台上具有不同的格式。 文件的路径可以是绝对路径或相对路径。 文件类有很多方法可用于创建,读取,删除或重命名文件。

This class extends Object class and implements Serializable interface. Declaration of the class is following.

此类扩展了Object类并实现了Serializable接口。 该类的声明如下。

宣言 (Declaration)

public class File extends Object implements Serializable, Comparable<File>

The File class is located into java.io package so we need to import the package to use its functionality.

File类位于java.io包中,因此我们需要导入该包以使用其功能。

以下是文件类的字段。 (Following are the fields of File Class.)

S.noFieldDescription
1pathSeparatorIt is represented as a string and it is used to separate the characters of the path.
2pathSeparatorCharIt is used as a path separator character.
3separatorIt is represented as a string and it is used to separate the characters of the path. It is a default name separator.
4separatorCharIt is represented as a string and it is used to separate the characters of the path.It is a default name separator.
序号 领域 描述
1个 pathSeparator 它表示为字符串,用于分隔路径的字符。
2 pathSeparatorChar 它用作路径分隔符。
3 分隔器 它表示为字符串,用于分隔路径的字符。 这是默认的名称分隔符。
4 分隔符 它以字符串表示,用于分隔路径的字符,这是默认的名称分隔符。

以下是文件类的构造函数。 (Following are the Constructors of File Class.)

1. File(File parent, String child)

1. File(文件父级,String子级)

2. File(String pathname)

2.文件(字符串路径名)

3. File(String parent, String child)

3. File(String父级,String子级)

4. File(URI uri)

4.文件(URI uri)

以下是文件类的方法。 (Following are the methods of File Class.)

S.no.MethodDescription
1createTempFile(String prefix, String suffix)It is used to create an empty file.
2createNewFile()It is used for creating a new file, which is empty and has an abstract pathname.
3canWrite()It is used to check whether the application can modify a file which has an abstract path.
4canExecute()It is used to check whether the application can execute a file which has an abstract path.
5canRead()It is used to check whether the application can read a file which has an abstract path
6isAbsolute()It is used to check whether the abstract pathname is absolute or not.
7isDirectory()It is used to check whether the file with abstract pathname is a directory.
8isFile()It is used to check whether the file with abstract pathname is a file.
9getName()It is used to get the name of the file.
10getParent()It is used to get the name of the Parent file
11toPath()It is used to get objects of java.nio.file.Path.
12toURI()It is used to create a URL of a file with abstract pathname.
13listFiles()It is used for getting an array of the abstract pathname.
14getFressSpace()It is used for getting the number of unallocated bytes.
15list(FilenameFilter filter)It is used for getting an array of string with the name of the file which have abstract pathname.
16mkdir()It is used to create directory name.
序号 方法 描述
1个 createTempFile(字符串前缀,字符串后缀) 它用于创建一个空文件。
2 createNewFile() 它用于创建一个新文件,该文件为空并且具有抽象路径名。
3 canWrite() 它用于检查应用程序是否可以修改具有抽象路径的文件。
4 canExecute() 它用于检查应用程序是否可以执行具有抽象路径的文件。
5 可以阅读() 它用于检查应用程序是否可以读取具有抽象路径的文件
6 isAbsolute() 它用于检查抽象路径名是否是绝对路径。
7 isDirectory() 用于检查具有抽象路径名的文件是否为目录。
8 isFile() 用于检查具有抽象路径名的文件是否为文件。
9 getName() 用于获取文件名。
10 getParent() 用于获取父文件的名称
11 toPath() 它用于获取java.nio.file.Path的对象。
12 toURI() 它用于创建具有抽象路径名的文件的URL。
13 listFiles() 它用于获取抽象路径名的数组。
14 getFressSpace() 它用于获取未分配的字节数。
15 列表(FilenameFilter过滤器) 它用于获取具有文件名的字符串数组,该文件名具有抽象路径名。
16 mkdir() 它用于创建目录名称。

示例:创建文件 (Example : Creating a File)

Lets start working with file by creating a new file. To create a file, we are using createNewFile method that takes filename as an argument. This method creates a new file if file is not already exist. See the example below.

让我们通过创建一个新文件开始使用文件。 要创建文件,我们使用createNewFile方法,该方法以filename为参数。 如果文件不存在,则此方法将创建一个新文件。 请参见下面的示例。

import java.io.File; 
import java.io.IOException;  

public class FileCreateDemo1
{
        public static void main(String[] args) 
        {
        	try 
        	{
        		File Obj = new File("FileDemo.txt");
        		if (Obj.createNewFile())	{
			        System.out.println("******File created******");
               		  System.out.println("Name of the file = " + Obj.getName());
                  } 
                else{
			       System.out.println("File already exists.");
                }
        } 
        catch (IOException e){
	        e.printStackTrace();
        }
   }
}
create-file

示例:写入文件 (Example: Writing in a file)

After creating a file, now will write data to the file. To write data, a method of Filewrite class is used. It will write the data but may throw exception so make sure to handle the excecptions as well.

创建文件后,现在将数据写入文件。 要写入数据,使用Filewrite类的方法。 它将写入数据,但可能会引发异常,因此请确保也处理异常。

import java.io.FileWriter;   
import java.io.IOException;  

public class FileWriteDemo1 
{
  public static void main(String[] args) 
{
    try 
	{
		FileWriterobj = new FileWriter("FileDemo.txt");
		obj.write("Welcome to studytonight.com.");
		obj.close();
		System.out.println("File is Updated.");
	}
    catch (IOException e) 
	{
		e.printStackTrace();
	}
  }
}
write-file

write-file

示例:读取文件 (Example : Reading a file)

To read data from the file we used File and Scenner classes both are used to handle input and output of system resources. Here we are using two method hasNextLine() and nextLine() to read the data sequentially.

为了从文件中读取数据,我们使用File和Scenner类来处理系统资源的输入和输出。 在这里,我们使用hasNextLine()nextLine()这两种方法顺序读取数据。

import java.io.File;  
import java.io.FileNotFoundException;  
import java.util.Scanner; 

public class FileReadDemo1
{
 	 public static void main(String[] args) 
        {
 	       try 
 	       {
                File Obj = new File("FileDemo.txt");
                Scanner obj1 = new Scanner(Obj);
                while (obj1.hasNextLine()) 
                {
        		  String obj2 = obj1.nextLine();
       		  System.out.println(obj2);
                }
                obj1.close();
        	}catch (FileNotFoundException e) 
            {
                e.printStackTrace();
            }
        }
}
reading-file

示例:复制文件 (Example : Copying a file)

Lets take another example to copy data of one file to another. Here we are using fileinput and output streams to read and write data. Although this is just a procedure to copy one file data to another whereas Java provides built-in methods to direct copy one file data to another file. See the below example.

让我们举另一个例子将一个文件的数据复制到另一个文件。 在这里,我们使用文件输入和输出流来读取和写入数据。 尽管这只是将一个文件数据复制到另一个文件的过程,而Java提供了内置方法将一个文件数据直接复制到另一个文件。 请参见以下示例。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopyDemo1 {
    public static void main(String[] args) {
        FileInputStream a = null;
        FileOutputStream b = null;
        try {
            File obj_in = new File("FileDemo.txt");
            File obj_out = new File("FileDemo1.txt");

            a = new FileInputStream(obj_in);
            b = new FileOutputStream(obj_out);

            byte[] buffer = new byte[1024];

            int length;
            while ((length = a.read(buffer)) > 0) {
                b.write(buffer, 0, length);
            }
            a.close();
            b.close();
            System.out.println("File copied successfully!!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
copy-file

copy-file

档案权限 (File permissions)

We can check permissions like: reading, writing, deleting etc of a file by using the built-in methods. The File class provides methods canRead(), canWrite() etc to check whether the operation is permissible or not.

我们可以使用内置方法来检查权限,例如:读取,写入,删除文件等。 File类提供方法canRead()canWrite()等,以检查该操作是否允许。

import java.io.*;

public class FilePermissionDemo1 {
    public static void main(String[] args) {
        File a = new File("FileDemo1.txt");

        boolean b = a.exists();
        if (b == true) {
            System.out.println("Executable: " + a.canExecute());
            System.out.println("Readable: " + a.canRead());
            System.out.println("Writable: " + a.canWrite());
        } else {
            System.out.println("File not found.");
        }
    }
}
file-permission

检索文件信息 (Retrieving file information)

This is one of the important part of file handling, getting metadata of a file is necessary to keep the information about the file like: type of file, location of file, permissions of file etc. in this example, we are using some built-in methods of File class to get information about the file. See the below example

这是文件处理的重要部分之一,获取文件的元数据对于保持有关文件的信息非常必要,例如:文件类型,文件位置,文件权限等。在此示例中,我们使用了一些内置的在File类的方法中获取有关文件的信息。 见下面的例子

import java.io.File;  
public class FileInfoDemo1
{ 
  public static void main(String[] args) 
	{
		File Obj = new File("FileDemo1.txt");
		if (Obj.exists()) 
		{
			System.out.println("File name= " + Obj.getName());
			System.out.println("***********************************");
			System.out.println("Absolute path= " + Obj.getAbsolutePath());
			System.out.println("***********************************");
			System.out.println("Writeable= " + Obj.canWrite());
			System.out.println("***********************************");
			System.out.println("Readable= " + Obj.canRead());
			System.out.println("***********************************");
			System.out.println("File size in bytes= " + Obj.length());
		} 
		else 
		{
			System.out.println("file does not exist.");
		}
	}
}
retrieve-file

删除文件 (Deleting a file)

In case, we need to delete a file then Java provides the method delete() that helps to delete a file using a code. In this example, we are deleting file. The method returns a boolean value to ensure that file has deleted successfully.

如果需要删除文件,那么Java提供了delete()方法,该方法有助于使用代码删除文件。 在此示例中,我们正在删除文件。 该方法返回一个布尔值,以确保文件已成功删除。

import java.io.File;
public class FileDeleteDemo1 {
    public static void main(String[] args) {
        File Obj = new File("FileDemo.txt");
        if (Obj.delete()) {
            System.out.println(Obj.getName() + " has been deleted");
        } else {
            System.out.println("Failed");
        }
    }
}
delete-file

翻译自: https://www.studytonight.com/java/file-handling.php

java file类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值