欢迎访问宙启技术站
智能推送

Java函数怎样实现文件读写操作?

发布时间:2023-06-21 18:25:20

Java 提供了丰富的 API 来实现文件读写操作,包括文件的读取、写入、重命名、删除等。

## 文件的读取

Java 以文件输入流(InputStream)和文件读取器(Reader)的方式来实现文件读取操作。下面是一个简单的示例代码,演示了如何使用文件读取器读取文件内容:

import java.io.*;

public class FileReaderExample {
    public static void main(String[] args) {
        try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

该示例代码中,我们使用了 try-with-resources 语法来自动关闭文件读取器。在 try 块中,我们创建了一个文件读取器 reader,并且使用它的 readLine() 方法来读取文件的每一行内容,并将其输出到控制台上。

## 文件的写入

Java 以文件输出流(OutputStream)和文件写入器(Writer)的方式来实现文件写入操作。下面是一个简单的示例代码,演示了如何使用文件写入器来写入文件内容:

import java.io.*;

public class FileWriterExample {
    public static void main(String[] args) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"))) {
            writer.write("Hello, world!");
            writer.newLine();
            writer.write("This is an example of file writing.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

该示例代码中,我们使用了 try-with-resources 语法来自动关闭文件写入器。在 try 块中,我们创建了一个文件写入器 writer,并使用它的 write() 方法来写入文件内容,“Hello, world!” 和 “This is an example of file writing.” 分别代表文件的两行内容。

## 文件的复制和移动

Java 可以使用文件输入输出流实现文件的复制和移动。下面是一个简单的示例代码,演示了如何使用文件输入输出流将文件从指定路径复制到另一路径:

import java.io.*;

public class FileCopyExample {
    public static void main(String[] args) {
        String srcPath = "example.txt";
        String destPath = "example_copy.txt";

        try (InputStream in = new FileInputStream(new File(srcPath));
             OutputStream out = new FileOutputStream(new File(destPath))) {
            byte[] buffer = new byte[8192];
            int len;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

该示例代码中,我们首先指定源文件的路径 srcPath 和目标路径 destPath。然后我们使用文件输入输出流 FileInputStream 和 FileOutputStream 来读取和写入文件内容,最后将文件复制到目标路径。

Java 还提供了一个 Files 类,它可以更方便地实现文件的复制、移动、重命名和删除操作。下面是一个简单的示例代码,演示了如何使用 Files 类的方法来实现文件复制和移动操作:

import java.io.*;
import java.nio.file.*;

public class FilesExample {
    public static void main(String[] args) {
        String srcPath = "example.txt";
        String destPath = "example_copy.txt";
        String movePath = "example_move.txt";

        try {
            // 复制文件
            Path src = Paths.get(srcPath);
            Path dest = Paths.get(destPath);
            Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);

            // 移动文件
            Path move = Paths.get(movePath);
            Files.move(dest, move, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

## 文件的删除

Java 可以使用 File 类或 Files 类实现文件的删除操作。下面是一个简单的示例代码,演示了如何使用 File 类和 Files 类的方法来删除文件:

import java.io.*;
import java.nio.file.*;

public class FileDeleteExample {
    public static void main(String[] args) {
        String filePath = "example.txt";

        // 使用 File 类删除文件
        File file = new File(filePath);
        if (file.delete()) {
            System.out.println("File deleted successfully");
        } else {
            System.out.println("Failed to delete the file");
        }

        // 使用 Files 类删除文件
        Path path = Paths.get(filePath);
        try {
            Files.delete(path);
            System.out.println("File deleted successfully");
        } catch (NoSuchFileException e) {
            System.out.println("File not found.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

该示例代码中,我们首先指定要删除的文件的路径 filePath。然后我们使用 File 类的 delete() 方法和 Files 类的 delete() 方法来删除文件,如果删除成功则输出 “File deleted successfully”,否则输出 “Failed to delete the file” 或 “File not found.”。需要注意的是,Files 类的 delete() 方法如果无法找到指定文件时,会抛出 NoSuchFileException 异常。