📜  Java中的文件处理

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

Java中的文件处理

在Java中,借助 File Class,我们可以处理文件。该文件类位于Java.io 包中。可以通过创建类的对象然后指定文件名来使用 File 类。

为什么需要文件处理?

  • 文件处理是任何编程语言不可或缺的一部分,因为文件处理使我们能够将任何特定程序的输出存储在文件中,并允许我们对其执行某些操作。
  • 简而言之,文件处理意味着读取数据并将数据写入文件。
Java
// Importing File Class
import java.io.File;
  
class GFG {
    public static void main(String[] args)
    {
  
        // File name specified
        File obj = new File("myfile.txt");
          System.out.println("File Created!");
    }
}


Java
// Import the File class
import java.io.File;
  
// Import the IOException class to handle errors
import java.io.IOException;
  
public class GFG {
    public static void main(String[] args)
    {
  
        try {
            File Obj = new File("myfile.txt");
            if (Obj.createNewFile()) {
                System.out.println("File created: "
                                   + Obj.getName());
            }
            else {
                System.out.println("File already exists.");
            }
        }
        catch (IOException e) {
            System.out.println("An error has occurred.");
            e.printStackTrace();
        }
    }
}


Java
// Import the File class
import java.io.File;
  
// Import this class for handling errors
import java.io.FileNotFoundException; 
  
// Import the Scanner class to read content from text files
import java.util.Scanner; 
  
public class GFG {
    public static void main(String[] args)
    {
        try {
            File Obj = new File("myfile.txt");
            Scanner Reader = new Scanner(Obj);
            while (Reader.hasNextLine()) {
                String data = Reader.nextLine();
                System.out.println(data);
            }
            Reader.close();
        }
        catch (FileNotFoundException e) {
            System.out.println("An error has occurred.");
            e.printStackTrace();
        }
    }
}


Java
// Import the FileWriter class
import java.io.FileWriter; 
  
// Import the IOException class for handling errors
import java.io.IOException; 
  
public class GFG {
    public static void main(String[] args)
    {
        try {
            FileWriter Writer
                = new FileWriter("myfile.txt");
            Writer.write(
                "Files in Java are seriously good!!");
            Writer.close();
            System.out.println("Successfully written.");
        }
        catch (IOException e) {
            System.out.println("An error has occurred.");
            e.printStackTrace();
        }
    }
}


Java
// Import the File class
import java.io.File; 
  
public class GFG {
    public static void main(String[] args)
    {
        File Obj = new File("myfile.txt");
        if (Obj.delete()) {
            System.out.println("The deleted file is : "
                               + myObj.getName());
        }
        else {
            System.out.println(
                "Failed in deleting the file.");
        }
    }
}


输出

File Created!

在Java中,概念 Stream 用于对文件执行 I/O 操作。所以首先,让我们熟悉一个在Java中称为 Stream 的概念。

Java中的流

  • 在Java中,数据序列称为流。
  • 此概念用于对文件执行 I/O 操作。
  • 有两种类型的流:

1.输入流:

Java InputStream 类是所有输入流的超类。输入流用于从键盘、网络等众多输入设备读取数据。 InputStream 是一个抽象类,因此,它本身没有用处。但是,它的子类用于读取数据。

InputStream类有几个子类,如下:

  1. 音频输入流
  2. 字节数组输入流
  3. 文件输入流
  4. 过滤输入流
  5. 字符串缓冲区输入流
  6. 对象输入流

创建一个输入流

// Creating an InputStream
InputStream obj = new FileInputStream();

在这里,使用 FileInputStream 创建一个输入流。

InputStream 的方法

S No.MethodDescription
1read()Reads one byte of data from the input stream.
2read(byte[] array)()Reads byte from the stream and stores that byte in the specified array.
3mark()It marks the position in the input stream until the data has been read.
4available()Returns the number of bytes available in the input stream.
5markSupported()It checks if the mark() method and the reset() method is supported in the stream.
6reset()Returns the control to the point where the mark was set inside the stream.
7skips() Skips and removes a particular number of bytes from the input stream.
8close()Closes the input stream.

2.输出流:

输出流用于将数据写入监视器、文件等众多输出设备。OutputStream 是表示输出流的抽象超类。 OutputStream 是一个抽象类,因此,它本身没有用。但是,它的子类用于写入数据。

OutputStream 类有几个子类,如下所示:

  1. 字节数组输出流
  2. 文件输出流
  3. 字符串缓冲区输出流
  4. 对象输出流
  5. 数据输出流
  6. 打印流

创建一个输出流

// Creating an OutputStream
OutputStream obj = new FileOutputStream();

在这里,使用 FileOutputStream 创建一个输出流。

OutputStream 的方法

S. No.MethodDescription
1.write()Writes the specified byte to the output stream.
2.write(byte[] array)Writes the bytes which are inside a specific array to the output stream.
3.close()Closes the output stream.
4.flush()Forces to write all the data present in an output stream to the destination.

根据数据类型,有两种类型的流:

1.字节流:

此流用于读取或写入字节数据。字节流再次细分为两种类型,如下所示:

  • 字节输入流:用于从不同设备读取字节数据。
  • 字节输出流:用于将字节数据写入不同的设备。

2.字符流:

此流用于读取或写入字符数据。字符流又细分为以下两种:

  • 字符输入流:用于从不同设备读取字符数据。
  • 字符输出流:用于将字符数据写入不同的设备。

由于您知道什么是流,让我们通过进一步了解对文件执行操作(如创建、读取和写入文件)有用的各种方法来完善Java中的文件处理。

Java文件类方法

下表描述了几种文件类方法:

Method NameDescriptionReturn Type
canRead() It tests whether the file is readable or not. Boolean
canWrite()It tests whether the file is writable or not.Boolean
createNewFile()It creates an empty file.Boolean
delete()It deletes a file.Boolean
exists()It tests whether the file exists or not.Boolean
length()Returns the size of the file in bytes.Long
getName() Returns the name of the file.String
list()Returns an array of the files in the directory.String[] 
mkdir() Creates a new directory.Boolean
getAbsolutePath()Returns the absolute pathname of the file.String

现在让我们熟悉Java中的各种文件操作。

Java中的文件操作

以下是可以在Java中对文件执行的几种操作:

  • 创建文件
  • 从文件中读取
  • 写入文件
  • 删除文件

现在让我们详细研究上述每个操作。

1. 创建文件

  • 为了在Java中创建文件,您可以使用 createNewFile() 方法。
  • 如果文件创建成功,如果文件已经存在,它将返回一个布尔值 true 和 false。

以下是如何在Java中创建文件的演示:

Java

// Import the File class
import java.io.File;
  
// Import the IOException class to handle errors
import java.io.IOException;
  
public class GFG {
    public static void main(String[] args)
    {
  
        try {
            File Obj = new File("myfile.txt");
            if (Obj.createNewFile()) {
                System.out.println("File created: "
                                   + Obj.getName());
            }
            else {
                System.out.println("File already exists.");
            }
        }
        catch (IOException e) {
            System.out.println("An error has occurred.");
            e.printStackTrace();
        }
    }
}

输出

An error has occurred.

2. 从文件中读取:我们将使用 Scanner 类从文件中读取内容。以下是如何从Java中读取文件内容的演示:

Java

// Import the File class
import java.io.File;
  
// Import this class for handling errors
import java.io.FileNotFoundException; 
  
// Import the Scanner class to read content from text files
import java.util.Scanner; 
  
public class GFG {
    public static void main(String[] args)
    {
        try {
            File Obj = new File("myfile.txt");
            Scanner Reader = new Scanner(Obj);
            while (Reader.hasNextLine()) {
                String data = Reader.nextLine();
                System.out.println(data);
            }
            Reader.close();
        }
        catch (FileNotFoundException e) {
            System.out.println("An error has occurred.");
            e.printStackTrace();
        }
    }
}

输出

An error has occurred.

3. 写入文件:我们使用 FileWriter 类及其 write() 方法将一些文本写入文件。以下是如何在Java中将文本写入文件的演示:

Java

// Import the FileWriter class
import java.io.FileWriter; 
  
// Import the IOException class for handling errors
import java.io.IOException; 
  
public class GFG {
    public static void main(String[] args)
    {
        try {
            FileWriter Writer
                = new FileWriter("myfile.txt");
            Writer.write(
                "Files in Java are seriously good!!");
            Writer.close();
            System.out.println("Successfully written.");
        }
        catch (IOException e) {
            System.out.println("An error has occurred.");
            e.printStackTrace();
        }
    }
}

输出

An error has occurred.

4. 删除文件:我们使用 delete() 方法来删除文件。以下是如何在Java中删除文件的演示:

Java

// Import the File class
import java.io.File; 
  
public class GFG {
    public static void main(String[] args)
    {
        File Obj = new File("myfile.txt");
        if (Obj.delete()) {
            System.out.println("The deleted file is : "
                               + myObj.getName());
        }
        else {
            System.out.println(
                "Failed in deleting the file.");
        }
    }
}

输出

Failed in deleting the file.