I am trying really hard to make my code to print the files and the directories in the same way that the command 'tree' in unix print.
What do I need to do so it will work? I'm stuck on it to much hours :(
This is the class I created for simple implementation of tree command using the composite design pattern:
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class TreePrint {
private final Directory root;
public TreePrint(String path) {
root = new Directory(path);
}
public void printTree(){
root.print(0);
}
private interface FileSystemComponent {
void print(int level);
}
private static class FileComponent implements FileSystemComponent{
private final String fileName;
public FileComponent(String name) {
fileName = name;
}
@Override
public void print(int level) {
printLevel(level);
System.out.println(fileName);
}
}
private static class Directory implements FileSystemComponent{
private final String directoryName;
private final List<FileSystemComponent> fileList = new ArrayList<>();
public Directory(String path) {
File directory = new File(path);
if(!directory.exists()){
throw new IllegalArgumentException("Invalid path, please try again");
}
directoryName = directory.getName();
File[] components = directory.listFiles();
if(null != components) {
for (File file : components) {
if (file.isDirectory()) {
fileList.add(new Directory(file.getPath()));
} else {
fileList.add(new FileComponent(file.getName()));
}
}
}
}
@Override
public void print(int level) {
printLevel(level);
System.out.println(colorTextToBlue(directoryName));
for(FileSystemComponent file : fileList) {
file.print(level + 1);
}
}
}
private static void printLevel(int level){
System.out.print("├──");
for (int i = 0; i < level; ++i) {
System.out.print("──");
}
}
private static String colorTextToBlue(String text){
final String blueBold = "\033[1;34m";
final String reset = "\033[0m";
return blueBold + text + reset;
}
}
For example, I want to print like this:
├── makefile
├── quiz19.c
├── stack_min.c
└── stack_min.h
but it's print like this:
├──quiz19
├────makefile
├────quiz19.c
├────stack_min.c
├────stack_min.h
(I still wan't the root on top, but i just want the lines to be the same like int the last file)
└──rather than├──?