Can anyone tell me what's wrong with my code? Since the third condition ("The contents of every file that is 50 bytes or smaller must be sorted by file name and written to the allFilesContent.txt file.") passes, you would think the first and second condition must pass as well. As for the fourth condition, the try-with-resources block should be auto-closing the streams anyway.
package com.codegym.task.task31.task3101;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
/*
Iterating through a file tree
*/
public class Solution {
public static void main(String[] args) {
String directoryPath = args[0];
String resultFileAbsolutePath = args[1];
File directory = new File(directoryPath);
File resultFile = new File(resultFileAbsolutePath);
List<File> files = allFilesInDirectory(directory);
List<File> filesLessThan50Bytes = files.stream().filter(file -> file.length() <= 50).collect(Collectors.toList());
List<File> sortedFilesLessThan50Bytes = filesLessThan50Bytes.stream().sorted(Comparator.comparing(File::getName)).collect(Collectors.toList());
FileUtils.renameFile(resultFile, new File(resultFile.getParent() + File.separator + "allFilesContent.txt"));
try (FileOutputStream fos = new FileOutputStream(resultFile)) {
for (File file : sortedFilesLessThan50Bytes) {
try (FileInputStream fis = new FileInputStream(file)) {
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fos.write(buffer);
fos.write("\n".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static List<File> allFilesInDirectory(File directory) {
List<File> files = new ArrayList<>();
for (File file : directory.listFiles()) {
if (file.isFile())
files.add(file);
else if (file.isDirectory())
files.addAll(allFilesInDirectory(file));
}
return files;
}
}