任务描述
本关任务:把给定的多个文件合并成一个文件。
编程要求
仔细阅读右侧编辑区内给出的代码框架及注释,在 Begin-End 间编写程序代码,把给定的多个文件合并成一个文件。具体要求如下:
注意:请按照子文件后缀数字按照从小到大依次合并到目标文件。
- import java.io.*;
- import java.util.Scanner;
-
- public class FileTest {
-
- public static void main(String[] args) throws IOException {
-
- Scanner scanner = new Scanner(System.in); // 获取给定字符串
- String s = scanner.nextLine();
-
- // 请在Begin-End间编写完整代码
- /********** Begin **********/
- // 切割给定字符串,得到子文件目录和目标文件名
- String[] array = s.split(",");
- // 循环读取子文件内容,写入到目标文件
- File file1 = new File(array[0]);
- File file2 = new File(array[1]);
- FileOutputStream fileOutputStream = new FileOutputStream(file2);
- for (int i = 1; i < file1.listFiles().length; i ++){
- FileInputStream fileInputStream = new FileInputStream(array[0] + "/" + array[1] + "-" + i);
- int len = 0;
- while((len = fileInputStream.read()) != -1)
- fileOutputStream.write(len);
- }
- fileOutputStream.close();
- // 输出目标文件大小
- System.out.println("最后目标文件的大小:" + file2.length() + "字节");
- FileReader fileReader = new FileReader(array[1]);
- int lenx = 0;
- while((lenx = fileReader.read()) != -1){
- System.out.print((char)lenx);
- }
- fileReader.close();
-
- /********** End **********/
-
- }
- }