Answer the question
In order to leave comments, you need to log in
Why does out.write write null?
The main() method takes two parameters as input.
The first one is filePath - the path to the directory, the second one - resultFileAbsolutePath - the name (full path) of an existing file that will contain the result. Rename resultFileAbsolutePath to allFilesContent.txt . For each file in the filePath directory and all its nested subdirectories, do the following:
If the file has a length in bytes NOT greater than 50, then for all such files:
- Sort them by filename in ascending order, ignoring the path when sorting.
- In allFilesContent.txt, sequentially write the contents of all files of the sorted files. Write "\n" after each file body.
All files have a .txt extension.
I just can't figure out why null is written to allFilesContent.txt, all text files from the test directory are < 50 bytes.
File filePath = new File(args[0]);
File resultAbsolutePath = new File(args[1]);
File destination = new File(resultAbsolutePath.getParent() + "/allFilesContent.txt");
FileUtils.renameFile(resultAbsolutePath, destination);
ArrayList<File> fileList = getFileList(filePath);
FileOutputStream out = new FileOutputStream(destination);
Collections.sort(fileList);
for(int i = 0; i < fileList.size(); i++){
FileInputStream stream = new FileInputStream(fileList.get(i));
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String str;
while((str = reader.readLine()) != null){
str += str;
}
stream.close();
reader.close();
out.write((str + "\n").getBytes());
out.flush();
}
out.close();
}
public static ArrayList<File> getFileList(File path) {
ArrayList<File> list = new ArrayList<>();
for (File file : path.listFiles()) {
if (file.isDirectory()) {
ArrayList<File> proxyFileList = getFileList(file);
list.addAll(proxyFileList);
} else if (file.length() <= 50) {
list.add(file);
}
}
Answer the question
In order to leave comments, you need to log in
In your case, str is constantly overwritten and null is written to str in the last loop
String str;
while((str = reader.readLine()) != null){
str += str;
}
String resultStr;
String line;
while((line = reader.readLine()) != null){
resultStr += line;
}
String resultStr = String.join("\n", Files.readAllLines(file.toPath()));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question