下面是用Java编写的一个可以读取文件夹中的文件,并将两个文件合并保存在本地的功能代码示例:

import java.io.*;

public class FileMerger {
    public static void main(String[] args) {
        // 文件夹路径
        String folderPath = "path/to/folder";
        // 第一个文件名
        String fileName1 = "file1.txt";
        // 第二个文件名
        String fileName2 = "file2.txt";
        // 合并后的文件名
        String mergedFileName = "mergedFile.txt";

        // 创建合并后的文件
        File mergedFile = new File(folderPath + "/" + mergedFileName);

        try {
            // 创建文件输出流
            FileOutputStream fos = new FileOutputStream(mergedFile);
            // 创建缓冲区输出流
            BufferedOutputStream bos = new BufferedOutputStream(fos);

            // 读取第一个文件内容并写入合并文件
            File file1 = new File(folderPath + "/" + fileName1);
            FileInputStream fis1 = new FileInputStream(file1);
            BufferedInputStream bis1 = new BufferedInputStream(fis1);
            byte[] buffer1 = new byte[(int) file1.length()];
            bis1.read(buffer1);
            bos.write(buffer1);
            bis1.close();

            // 读取第二个文件内容并写入合并文件
            File file2 = new File(folderPath + "/" + fileName2);
            FileInputStream fis2 = new FileInputStream(file2);
            BufferedInputStream bis2 = new BufferedInputStream(fis2);
            byte[] buffer2 = new byte[(int) file2.length()];
            bis2.read(buffer2);
            bos.write(buffer2);
            bis2.close();

            // 关闭缓冲区输出流
            bos.close();

            System.out.println("文件合并成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

请根据实际情况将代码中的folderPathfileName1fileName2mergedFileName替换为实际的文件夹路径、文件名和合并后的文件名。运行上述代码后,合并后的文件将保存在指定文件夹中

用Java写一个功能能读取文件夹中的文件并将两个文件合并之后保存在本地

原文地址: https://www.cveoy.top/t/topic/hZx9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录