Java中IO流中的文件以及文件的常用操作

161 阅读3分钟

IO流中的文件

在Java语言中,I/O流是指一种用于读写数据的机制。文件I/O流主要是处理文件读写的操作,Java中的文件I/O操作主要是围绕File类和相关的输入输出流进行的。

在Java中,File类用于处理文件和目录的信息,它提供了很多方法来操作文件和目录,包括创建、删除、重命名、查询等操作。InputStream和OutputStream类是处理字节流的输入输出流,Reader和Writer类是处理字符流的输入输出流。FileInputStream、FileOutputStream、FileReader和FileWriter类是用于文件I/O操作的常用类。

主要分为五种类型

  1. 字节流(InputStream和OutputStream):以字节为单位进行读写操作的流。适用于二进制文件或者其他无法用文本方式表示的数据。
  2. 字符流(Reader和Writer):以字符为单位进行读写操作的流。适用于文本文件和其他能够用文本方式表示的数据。
  3. 缓冲流(BufferedInputStream和BufferedOutputStream、BufferedReader和BufferedWriter):对字节流和字符流进行缓冲处理,提高读写效率。
  4. 数据流(DataInputStream和DataOutputStream):可以按照Java基本数据类型的顺序读写基本数据类型的流。
  5. 对象流(ObjectInputStream和ObjectOutputStream):可以读写Java对象的流。

几个基本概念:

  1. 文件路径:文件路径用来表示文件在文件系统中的位置,可以是绝对路径或相对路径。
  2. 文件句柄:文件句柄是指打开文件时系统返回的唯一标识符,用于在文件I/O操作中指定文件。
  3. 文件指针:文件指针是指文件中正在读取或写入的位置。
  4. 文件状态:文件状态包括文件是否存在、是否可读、是否可写等。

文件的常用操作

在Java中,文件操作是经常需要用到的一种IO流操作。文件操作可以帮助我们读写文件,创建和删除文件等。

创建文件

在Java中,可以使用File类来创建文件。例如,下面的代码会创建一个名为“example.txt”的文件。

File file = new File("example.txt");

try {
    if (file.createNewFile()) {
        System.out.println("File created successfully.");
    } else {
        System.out.println("File already exists.");
    }
} catch (IOException e) {
    System.out.println("An error occurred.");
    e.printStackTrace();
}

写入文件

在Java中,可以使用FileWriter类来写入文件。例如,下面的代码会将一个字符串写入名为“example.txt”的文件中。

File file = new File("example.txt");

try {
    FileWriter writer = new FileWriter(file);
    writer.write("Hello, world!");
    writer.close();
    System.out.println("File written successfully.");
} catch (IOException e) {
    System.out.println("An error occurred.");
    e.printStackTrace();
}

读取文件

在Java中,可以使用FileReader类来读取文件。例如,下面的代码会读取名为“example.txt”的文件中的内容,并将其打印到控制台上。

File file = new File("example.txt");

try {
    FileReader reader = new FileReader(file);
    int character;
    while ((character = reader.read()) != -1) {
        System.out.print((char) character);
    }
    reader.close();
} catch (IOException e) {
    System.out.println("An error occurred.");
    e.printStackTrace();
}

删除文件

在Java中,可以使用File类的delete()方法来删除文件。例如,下面的代码会删除名为“example.txt”的文件。

File file = new File("example.txt");

if (file.delete()) {
    System.out.println("File deleted successfully.");
} else {
    System.out.println("Failed to delete the file.");
}

复制文件

在Java中,可以使用File类的copy()方法来复制文件。例如,下面的代码会将名为“example.txt”的文件复制到名为“example_copy.txt”的文件中。

File sourceFile = new File("example.txt");
File destinationFile = new File("example_copy.txt");

try {
    Files.copy(sourceFile.toPath(), destinationFile.toPath());
    System.out.println("File copied successfully.");
} catch (IOException e) {
    System.out.println("An error occurred.");
    e.printStackTrace();
}