编写将两个文件(文件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); } } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 metadata提取的PDF元数据,如何转换为一个Excel
- ¥15 关于arduino编程toCharArray()函数的使用
- ¥100 vc++混合CEF采用CLR方式编译报错
- ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
- ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
- ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
- ¥50 如何openEuler 22.03上安装配置drbd
- ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
- ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
- ¥15 Windows11, backspace, enter, space键失灵