圥忈.425 2022-07-02 13:15 采纳率: 85.7%
浏览 30
已结题

java—输入输出流

编写将两个文件(文件1、文件2)中的内容合并成一个新文件(文件3)。合并方法是:从文件1读取一个字节放入文件3,在从文件2读取一个字节放入文件3,如此轮流直至某一个文件读完,再将较长文件中的剩余部分读取放入至文件3。可以使用图形界面或命令行参数输入三个文件名。

  • 写回答

1条回答 默认 最新

  • foreverliuyin 2022-07-05 16:42
    关注

    这是纯字节写入的,如果要字符的还要改

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    
    public class FileWriter {
    
        public static void main(String[] args) throws IOException {
            // TODO Auto-generated method stub
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    
            System.out.println("请输入文件1的路径:");
            // Reading data using readLine
            String path1 = reader.readLine();
    
            System.out.println("请输入文件2的路径:");
            // Reading data using readLine
            String path2 = reader.readLine();
    
            System.out.println("请输入文件3的路径:");
            // Reading data using readLine
            String path3 = reader.readLine();
    
            FileInputStream bStream = new FileInputStream(path1);
            byte[] b1 = bStream.readAllBytes();
            bStream.close();
            FileInputStream bStream2 = new FileInputStream(path2);
            byte[] b2 = bStream2.readAllBytes();
            bStream2.close();
    
            ArrayList<Byte> b3 = new ArrayList<Byte>();
            int i = 0;
            while (i < Math.max(b1.length, b2.length)) {
                if (i < b1.length) {
                    b3.add(b1[i]);
                }
                if (i < b2.length) {
                    b3.add(b2[i]);
                }
                i++;
            }
            byte[] brr = new byte[b3.size()];
            for (Byte b : b3) {
                brr[b3.indexOf(b)] = b;
            }
            File file = new File(path3);
            try (FileOutputStream fout = new FileOutputStream(file)) {
                fout.write(brr);
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 9月20日
  • 已采纳回答 9月12日
  • 创建了问题 7月2日

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分