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

在Java中如何实现文件读取与写入功能的函数

发布时间:2023-05-24 22:49:53

在Java中,可以使用File、FileInputStream、FileOutputStream、BufferedReader、BufferedWriter等类实现文件读取与写入功能的函数。

文件读取功能函数:

1. 使用FileInputStream读取文件,将文件中的内容读入到一个byte[]数组中:

public static byte[] readFileToByteArray(File file) throws IOException {
    FileInputStream inputStream = new FileInputStream(file);
    try {
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes);
        return bytes;
    } finally {
        inputStream.close();
    }
}

2. 使用BufferedReader读取文件,将文件中的内容读入到一个String中:

public static String readFileToString(File file) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(file));
    StringBuilder stringBuilder = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        stringBuilder.append(line);
    }
    reader.close();
    return stringBuilder.toString();
}

文件写入功能函数:

1. 使用FileOutputStream写入文件,将byte[]数组写入到文件中:

public static void writeByteArrayToFile(File file, byte[] data) throws IOException {
    FileOutputStream outputStream = new FileOutputStream(file);
    try {
        outputStream.write(data);
    } finally {
        outputStream.close();
    }
}

2. 使用BufferedWriter写入文件,将String写入到文件中:

public static void writeStringToFile(File file, String data) throws IOException {
    BufferedWriter writer = new BufferedWriter(new FileWriter(file));
    try {
        writer.write(data);
    } finally {
        writer.close();
    }
}

以上为文件读取与写入功能的一些示例代码,开发者可根据需求做相应的修改。需要注意的是,在文件读取与写入过程中,需要捕获IOException异常并进行相关处理。