?
package com.codegym.task.task31.task3101;
/*
Iterating through a file tree
*/
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String args[]) throws Exception {
boolean test = false;
if (test) {
args = new String[2];
args[0] = "C:/TESZT/TEXT";
args[1] = "C:/TESZT/TEXT/01/resultFileAbsolutePath.txt";
}
File originalTargetFile = new File(args[1]);
//if (!FileUtils.isExist(originalTargetFile)) return;
String parent = originalTargetFile.getParent();
String targetStr = parent + "/allFilesContent.txt";
File targetFile = new File(targetStr);
if (FileUtils.isExist(targetFile)) {
FileUtils.deleteFile(targetFile);
}
FileUtils.renameFile(originalTargetFile, targetFile);
if (test) {
System.out.println(parent);
System.out.println(targetStr);
}
File startDir = new File(args[0]);
// dirList will store all subdirectories and the base directory too
ArrayList<File> dirList = new ArrayList<>();
dirList.add(startDir);
dirLister(dirList) ; // call the directory explorer method
if (test) System.out.println(dirList);
ArrayList<String> fileList = new ArrayList<>();
// When we got all the subdirectories, it checks all the items in each one,
// and if it is a file and less than 50 then puts it into fileList:
for (int i=0; i<dirList.size(); i++) {
File[] dirTomb = dirList.get(i).listFiles();
for (int j = 0; j<dirTomb.length; j++) {
if (dirTomb[j].isFile() && dirTomb[j].length()<=50 ) {
// Since the fileList will have to be sorted by filename, I'll append
// the filenames before the full paths, so it will be easy to sort.
// The filename will have to be removed from the beginning of the
// string (after sorting). The added '*' char is definitely can not
// the part of filenames - so this char will help to find where have to
// split the string, and to get back the absolutePath will be easier this way.
fileList.add(dirTomb[j].getName() + "*" + dirTomb[j].getAbsolutePath());
}
}
}
if (test) System.out.println();
// sorting
Collections.sort(fileList);
if (test) for (String s : fileList) System.out.println(s);
try {
// read and write the filecontents to the targetFile
PrintStream ps = new PrintStream(targetFile);
FileInputStream fis;
byte[] fileContent;
for (String s : fileList) {
fis = new FileInputStream(s.substring(s.indexOf("*")+1));
fileContent = new byte[fis.available()];
fis.read(fileContent);
ps.write(fileContent);
ps.print("\n");
fis.close();
}
ps.close();
}
catch (Exception ignored) { }
}
// An explorer method. Searches and places all found subdirectories in the dirList,
// after the initial item(s) already added.
public static void dirLister (ArrayList<File> dirList) {
// Lists and checks all of the contents of the last directory added to dirList,
File[] dirTomb = dirList.get(dirList.size()-1).listFiles();
for (int i= 0; i<dirTomb.length; i++) {
if (dirTomb[i].isDirectory()) {
dirList.add(dirTomb[i]);
// if the found element is a directory, we start the exploration again with that:
dirLister(dirList);
}
}
}
}