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

Java文件处理函数,实现文件读写操作

发布时间:2023-08-23 15:28:56

Java文件处理函数主要通过使用 java.io 包中的类来实现对文件的读写操作。下面是一个示例代码,展示了几个常用的文件处理函数。

1. 文件读取:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileReadExample {

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

上面的代码使用 BufferedReader 类从文件中逐行读取内容,并将每行内容打印出来。

2. 文件写入:

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

public class FileWriteExample {

    public static void main(String[] args) {
        String fileName = "output.txt";
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
            writer.write("Hello, World!");
            writer.newLine();
            writer.write("This is a file write example.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

上述代码使用 BufferedWriter 类将内容写入到文件中。在其中使用 write() 函数写入一行文本,并使用 newLine() 函数在每行之间添加一个换行符。

3. 文件复制:

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

public class FileCopyExample {

    public static void main(String[] args) {
        String sourceFileName = "source.txt";
        String destinationFileName = "destination.txt";
        try (FileInputStream source = new FileInputStream(sourceFileName);
             FileOutputStream destination = new FileOutputStream(destinationFileName)) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = source.read(buffer)) != -1) {
                destination.write(buffer, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

上述代码使用 FileInputStream 类从源文件中读取字节内容,并使用 FileOutputStream 类将字节内容写入到目标文件中,从而实现了文件的复制。

以上示例代码给出了一些常见的文件处理函数示例,你可以在实际操作中根据需要进行相应的修改和调整。