Code works fine, but I'm getting this "recomendation from your mentor":
"The files should not be copied in the order they were added, but from the first part to the last"
I'm using a HashMap<Integer, File> and then a for(i) loop to read/write every file in order. I checked this with multiple *.txt.part* files and it works.
package com.codegym.task.task18.task1825;
import java.io.*;
import java.util.*;
/*
Building a file
*/
public class Solution {
public static void main(String[] args) throws Exception {
HashMap<Integer, File> files = new HashMap<>();
String original = readFileNamesToMap(files);
writeOriginal(original, files);
}
//Lee filenames y añade los correspondientes archivos al mapa
private static String readFileNamesToMap(HashMap<Integer, File> files) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String original = "";
while (true) {
String s = reader.readLine();
if (s.matches(".*\\.part\\d*")) {
//extrae el part number y añade el archivo al mapa
int partNo = Integer.parseInt(s.split("\\.part")[1]);
original = s.split("\\.part")[0];
files.put(partNo, new File(s));
//System.out.println(files.get(partNo).getName() + " added to " + original);
} else if (s.equals("end")) {
reader.close();
break;
}
}
return original;
}
//Crea el archivo combinado y lo escribe en orden con el buffer de cada .part#
private static void writeOriginal(String original, HashMap<Integer, File> map) throws Exception {
File joined = new File(original);
BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(joined));
for (int i = 1; i <= map.size(); i++) {
writer.write(buffer(map.get(i)));
}
writer.close();
}
//Lee un archivo a un buffer de bytes
private static byte[] buffer(File file) throws Exception {
BufferedInputStream reader = new BufferedInputStream(new FileInputStream(file));
byte[] b = new byte[reader.available()];
reader.read(b);
reader.close();
return b;
}
}