Potrebno je napraviti aplikaciju koja će da obavlja funkcije file managera. Od funkcionalnosti, aplikacija treba da obezbedi sledeće funkcije:
Preporuka je da se za ove operacije koriste komande, redom: LIST, INFO, CREATE_DIR, RENAME, COPY, MOVE, DELETE.
Treba ponuditi korisniku da izabere koju od operacija sa fajlom/folderom želi da obavi. Nakon što korisnik aplikacije u konzolu unese određenu komandu, aplikacija prikazuje poruku o prepoznatoj komandi (ili neprepoznatoj, ako je komanda neadekvatna) i nastavlja sa prikupljanjem potrebnih informacija za obavljanje navedene operacije (putanje i slično). Korisnik treba da unese putanju do željenog fajla; ne treba koristiti hard-kodirane putanje. Tu obratite pažnju da li se radi sa relativnim ili apsolutnim putanjama.
Brisanje i kopiranje nepraznih foldera trebalo bi uraditi rekurzivno (tj. „u dubinu“).
|
sisic99 11.02.2018 Одељци: Зид Питања и одговори Ивица sisic99 | Кључне речи: Java IT Akademija
|
0
|
Ово решење је инспирисано Линукс комндном линијом, што значи да не одговара у потпуности поставци задатка, односно садржи нешто више, те је потребно рефакторовати код. Програм је тестиран на Линукс Минту 18.2, требало би да функционише и на другим платформама.
Програм има и одређена ограничења, као што је на пример услов да путање које уноси корисник не садрже празнине (спејсове).
Програм парсира (рашчлањује) текст који уноси корисник и на основу тога извршава одговарајућу акцију. У оквиру командне линије у сваком тренутку приказан је активни директоријум. Активни директоријум се мења командом cd <putanja>. Поред команди и аргумената, неке од команди прихватају и опције, које се наводе иза цртице (знака минус -). Путање могу бити релативне или апсолутне. У следећој табели дат је комплетан списак команди:
| Промена активног директоријума | cd <putanja> |
| Преглед директоријума |
ls [<putanja>] |
| Преглед фајлова/директоријума у табеларном облику |
ls -l[a] [<putanja>] |
| Креирање директоријума. Опција -p креира све директоријуме из наведене путање | mkdir [-p] <direktorijum> |
| Промена имена и премештање фајлова/директоријума | mv <izvor> <odrediste> |
| Koпирање фајлова и директоријума. Опција -r се користи за директоријуме. | cp [-r] <izvor> <odrediste> |
| Брисање фајлова/директоријума. За брисање директоријума користити опцију -r | rm [-r] <izvor> <odrediste> |
package file_manager;
import java.util.*;
import java.io.*;
import java.nio.file.attribute.*;
import java.nio.file.*;
import static java.nio.file.StandardCopyOption.*;
/**
*
* @author ivica
*/
public class File_manager
{
private static String wd;
static final int ROW1 = 25;
static final int ROW2 = 55;
static final int ROW3 = 15;
static final int ROW4 = 20;
static final int ROW5 = 20;
static final String LEFT_ALIGN_FORMAT = "| %-"+String.valueOf(ROW1)+"s | %-"+String.valueOf(ROW2)+"s | %-"+String.valueOf(ROW3)+"s | %-"+String.valueOf(ROW4)+"s | %-"+String.valueOf(ROW5)+"s | %n";
public static String getWd()
{
return wd;
}
private static void setWd(String dir)
{
wd = dir;
}
private static String getPrompt()
{
return wd + " $ ";
}
private static void deleteDir(File file)
{
File[] contents = file.listFiles();
if (contents != null) {
for (File f : contents) {
deleteDir(f);
}
}
file.delete();
}
private static String rtrimSeparator(String path)
{
return path.replace(File.separator+"+$", "");
}
/**
*
* @param source
* @param destination
*/
private static void copyDir(File source, File destination, boolean copy)
{
if (source.getAbsolutePath().equals(destination.getAbsolutePath())) {
return;
}
ArrayList<File> contents = new ArrayList<>();
contents.add(source);
ArrayList<File> newContents = new ArrayList();
String strDestination = rtrimSeparator(destination.getAbsolutePath());
String strSource = source.getAbsolutePath();
if (source.isDirectory() && destination.exists() && destination.isDirectory()) {
String[] arr = strSource.split(File.separator);
strDestination += File.separator + arr[arr.length-1];
File newDir = new File(strDestination);
newDir.mkdir();
} else if ( ! source.isDirectory() && destination.isDirectory()) {
strDestination += File.separator + filename(source);
}
while (contents.size() > 0) {
for (File f : contents) {
if (f.isDirectory()) {
File [] files = f.listFiles();
newContents.addAll(Arrays.asList(files));
}
String newPath = f.getAbsolutePath().replace(strSource, strDestination);
File destFile = new File(newPath);
try {
Files.copy(f.toPath(), destFile.toPath(), REPLACE_EXISTING);
} catch(IOException e) {
String action = copy ? "premeštanja" : "kopiranja";
throw new java.lang.RuntimeException("Greška prilikom "+action+" fajla " + f.getAbsolutePath() + " u " + destFile.getAbsolutePath());
}
}
contents = newContents;
newContents = new ArrayList<>();
}
}
private static String getAbsPath(String path)
{
File f = new File(path);
String ret = path;
if ( ! f.isAbsolute()) {
ret = getWd().replaceAll(File.separator + "*$", "") + File.separator + path;
}
//TODO izbaciti svako pojavljivanje .. iz putanje, kao i svaki direktorijum koji se nalazi ispred ..
//Na primer putanju /nesto/../xxx/yyy transformisati u /xxx/yyy
String test = ret.substring(ret.length()-2, ret.length());
if (ret.length() > 1 && test.equals("..")) {
String[] arr = ret.split(File.separator);
String[] newArr = Arrays.copyOf(arr, arr.length - 2);
ret = String.join(File.separator, newArr);
}
return ret;
}
private static String mkdir(ArrayList<String> args, ArrayList<String> opts)
{
if (args.size() != 2) {
return "Neodgovarajući broj argumenata";
}
String path = getAbsPathFromArgs(args, 1);
File dir = new File(path);
if (opts.contains("p")) {
dir.mkdirs();
} else {
dir.mkdir();
}
if ( ! dir.exists()) {
return "Greška prilikom kreiranja direktorijuma " + path;
}
return "";
}
private static String rm(ArrayList<String> args, ArrayList<String> opts)
{
String path = getAbsPathFromArgs(args, 1);
File f = new File(path);
if ( ! f.exists()) {
return path + " ne postoji";
}
if (f.isDirectory()) {
if (! opts.contains("r")) {
return path + " je direktorijum. Za brisanje direktorijuma navedite opciju -r";
}
try {
deleteDir(f);
} catch (java.lang.Exception e) {
return "Greška prilikom brisanja direktorijuma " + path;
}
return "";
}
try {
f.delete();
} catch (java.lang.Exception e) {
return "Greška prilikom brisanja fajla " + path;
}
return "";
}
private static String cp(ArrayList<String> args, ArrayList<String> opts)
{
if (args.size() != 3) {
return "Neodgovarajući broj argumenata";
}
String source = getAbsPathFromArgs(args, 1);
String destination = getAbsPathFromArgs(args, 2);
File s = new File(source);
File d = new File(destination);
if ( ! s.exists()) {
return source + " ne postoji";
}
if (s.isDirectory() && ! opts.contains("r")) {
return source + " je direktorijum. Koristite opciju -r";
}
if (s.isDirectory() && d.exists() && ! d.isDirectory()) {
return "Nije moguće kopirati direktorijum u fajl";
}
try {
copyDir(s, d, true);
} catch(java.lang.Exception e) {
return e.getMessage();
}
return "";
}
private static String dirname(File f)
{
return f.getAbsolutePath().replace(File.separator +"+$", "").replace(File.separator+".*$", "");
}
private static String filename(File f)
{
return f.getName();
}
private static String mv(ArrayList<String> args, ArrayList<String> opts)
{
if (args.size() != 3) {
return "Neodgovarajući broj argumenata";
}
String source = getAbsPathFromArgs(args, 1);
String destination = getAbsPathFromArgs(args, 2);
File s = new File(source);
File d = new File(destination);
if ( ! s.exists()) {
return source + " ne postoji";
}
if (s.isDirectory() && d.exists() && ! d.isDirectory()) {
return "Nije moguće premestiti direktorijum u fajl";
}
try {
copyDir(s, d, false);
} catch(java.lang.Exception e) {
return e.getMessage();
}
deleteDir(s);
return "";
}
private static String cd(ArrayList<String> args)
{
String path = getAbsPathFromArgs(args, 1);
File dir = new File(path);
if ( ! dir.isDirectory()) {
return path + " nije direktorijum";
}
if ( ! dir.exists()) {
return path + " ne postoji";
}
wd = path;
return "";
}
private static String getAbsPathFromArgs(ArrayList<String> args, int index)
{
String path = getWd();
if (args.size() > index) {
path = args.get(index);
}
return getAbsPath(path);
}
private static String ls(ArrayList<String> args, ArrayList<String> opts)
{
String path = getAbsPathFromArgs(args, 1);
File dir = new File(path);
if ( ! dir.exists()) {
return "Traženi putanja ne postoji";
}
boolean optL = opts.contains("l");
String ret = list(dir, opts.contains("a"), optL);
if ( ! ret.equals("") && optL) {
StringBuilder sbuf = new StringBuilder();
Formatter fmt = new Formatter(sbuf);
fmt.format(LEFT_ALIGN_FORMAT,
"Naziv",
"Putanja",
"Veličina",
"Vreme kreiranja",
"Vreme izmene"
);
String border = "+---------------------------+---------------------------------------------------------+-----------------+----------------------+----------------------+\n";
String cols = sbuf.toString();
ret = border
+ cols
+ border
+ ret
+ border;
}
return ret;
}
private static String list(File dir, boolean optA, boolean optL)
{
String ret = "";
if (dir.isFile()) {
return fileInfo(dir, optL);
}
for (File file : dir.listFiles()) {
if (file.isHidden() && ! optA) {
continue;
}
ret += fileInfo(file, optL);
}
return ret;
}
private static String shortenString(String s, int len)
{
if (s.length() > len) {
return s.substring(0, Math.min(s.length(), len - 3)) + "...";
}
return s;
}
private static String fileInfo(File dir, boolean optL)
{
//Ako nije navedena opcija -l onda samo prikazuje naziv fajla ili direktorijuma
if ( ! optL) {
return dir.getName() + "\t";
}
//Navedena je opcija -l
Path path = Paths.get(dir.getAbsolutePath());
BasicFileAttributes attr;
try {
attr = Files.readAttributes(path, BasicFileAttributes.class, java.nio.file.LinkOption.NOFOLLOW_LINKS);
} catch (IOException e) {
throw new java.lang.RuntimeException("Greska prilikom citanja atributa fajla, "+ path);
}
StringBuilder sbuf = new StringBuilder();
Formatter fmt = new Formatter(sbuf);
fmt.format(LEFT_ALIGN_FORMAT,
shortenString(dir.getName(), ROW1) ,
shortenString(dir.getAbsolutePath(), ROW2),
attr.size(),
shortenString(attr.creationTime().toString(), ROW4),
shortenString(attr.lastModifiedTime().toString(), ROW5)
);
return sbuf.toString();
}
private static Map<String, ArrayList<String>> getParams(String line)
{
Map<String, ArrayList<String>> map = new HashMap<>();
String opts = "";
map.put("opts", new ArrayList<>());
map.put("args", new ArrayList<>());
if (line.trim().equals("")) {
return map;
}
String[] args = line.split("\\s");
for (String arg : args) {
if (arg.charAt(0) == '-') {
String newOpt = arg.substring(1);
if (newOpt.length() > 0) {
opts += newOpt;
}
} else {
map.get("args").add(arg);
}
}
map.get("opts").addAll(Arrays.asList(opts.split("")));
return map;
}
public static void main(String[] progArgs)
{
setWd(System.getProperty("user.dir"));
Scanner s = new Scanner(System.in).useDelimiter("\n");
String line;
System.out.print(getPrompt());
while ( ! (line = s.nextLine()).equals("q")) {
Map<String, ArrayList<String>> params = getParams(line);
ArrayList<String> arr = params.get("args");
String command = "";
if (arr.size() > 0) {
command = arr.get(0).toLowerCase();
}
ArrayList<String> args = params.get("args");
ArrayList<String> opts = params.get("opts");
String promptPrefix = "\n";
String out = "";
switch (command) {
case "ls":
out = ls(args, opts);
break;
case "cd":
out = cd(args);
break;
case "rm":
out = rm(args, opts);
break;
case "mkdir":
out = mkdir(args, opts);
break;
case "mv":
out = mv(args, opts);
break;
case "cp":
out = cp(args, opts);
break;
case "":
promptPrefix = "";
break;
default:
out = "Ne razumem komandu";
}
if ( ! out.equals("")) {
System.out.print(out);
} else {
promptPrefix = "";
}
System.out.print(promptPrefix + getPrompt());
}
}
}
Заинтересовани за часове програмирања могу ме контактирати путем мејла [email protected]
|
Ивица 15.03.2018 Одељци: Зид Питања и одговори Ивица | Кључне речи: Java IT Akademija |
0
|
©Библиотека++ 2025 Развој сајта Ивица Лазаревић