The validation is a bit off. As it claims I do not close the stream.
But maybe I am not allowed to use a TreeMap for this task?
package com.codegym.task.task18.task1825;
import java.io.*;
import java.util.Map;
import java.util.TreeMap;
/*
Building a file
*/
public class Solution {
public static void main(String[] args) throws IOException {
//Create a reader to read filenames from keyboard
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
//create a map for all filenames <String = .<partN>, String = fullFilename>
Map<String, String> folder = new TreeMap<>();// place all entries in order
//read filenames until "end" is entered
String s;
while (!(s = reader.readLine()).equals("end")) {
s = reader.readLine();//reads the filenames
//split the filenames .part<n> will be the key to be able to sort the files in the right order
String partNumber = s.substring(s.lastIndexOf(".part"));
folder.put(partNumber, s);
}
reader.close();
//create a file to which all content will be written to
String file = folder.get(0);//returns the value of the first file which is a fileName including the partNumber
String fileComposite = file.substring(0, file.lastIndexOf(".part"));//creates a fileName without the <.partN>
//folder.put(fileComposite, fileComposite); //not sure if I have to add this file to the folder/map
//create outputStream
FileOutputStream fos = new FileOutputStream(fileComposite, true);
//iterate over the map with filenames
for (String fileName : folder.values()) {
//create inputStream for each fileName
FileInputStream fis = new FileInputStream(fileName);
//create a buffer for all bytes read available() gives number of bytes to read
byte[] buffer = new byte[fis.available()];
//read the bytes from a file and add it to the buffer
while (fis.available() > 0) {
int byteRead = fis.read(buffer);
//write the buffer to outputStream file
fos.write(buffer, 0, byteRead);
}
fis.close();
}
fos.close();
}
}