I was commissioned to do an exercise that is as follows:
Make a program in Java that simulates a file browser.
Once the program has been executed, starting from the project folder, you must allow the user to perform the following actions:
- With "cd .." it will go to the folder. If it is in the root it will not do anything.
- With "cd name" you will go to the folder named "name". If it does not exist, it will give an error. "Name" can be a relative path to a folder or an absolute path to a folder.
- With "ls" it will show the contents of the current folder.
- With "ls -l" it will show the contents of the current folder indicating for each file and folder its size and modification date.
- With "quit" the program ends.
- With "the name" delete the file or folder named "name". If the folder is not empty, show the message "Folder name is not empty".
- With "del -r name" delete all the contents of the folder named "name" whether it is empty or not.
- With "mkdir name" creates the empty folder named "name". "Name" can be a relative or absolute path. It may be the case that they have to create folders in between.
- With "mv name1 name2" move the file or folder named "name1" to "name2". Both "name1" and "name2" will be absolute paths.
If the user enters a nonexistent order, "Error: invalid command" will be notified and nothing will be done.
But I was stuck, I hope you can help me, this is my piece of code:
package com.company;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner lector = new Scanner(System.in);
File ruta = new File("C:\Users\Victor\Desktop");
String comando = "";
do {
comando = lector.nextLine();
switch (comando) {
case "cd ..":
ruta = cedes(ruta);
break;
case "ls":
ruta = eleses(ruta,comando);
break;
case "ls -l":
ruta = eleses(ruta,comando);
break;
}
} while (!comando.equals("quit"));
}
public static File cedes(File ruta) {
if (!ruta.getParent().equals("/")) {
System.out.println(ruta.getParent());
ruta = new File(ruta.getParent());
}
return ruta;
}
public static File eleses(File ruta, String comando) {
if (comando.equals("ls")) {
String[] lista = ruta.list();
for (int i = 0; i < lista.length; i++) {
System.out.println(lista[i]);
}
return ruta;
}else if (comando.equals("ls -l")) {
String[] lista2 = ruta.list();
for (int i = 0; i < lista2.length; i++) {
System.out.println(lista2[i] + " " + ruta.lastModified());
}
}return ruta;
}
}