package commands; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.OutputStreamWriter; import kernel.AppException; import kernel.AbstractProcess; /** * @author Vaclav Podlena * */ public class ls extends AbstractProcess { /** * implentation of the ls command * * @throws AppException * Exception caused by an error in the virtual machines manager. */ public void realization() throws AppException { BufferedWriter out = new BufferedWriter(new OutputStreamWriter(this .getOut())); File dir = new File(getParentCurrentPath()); // Get the directory to list if (getArgs().size() > 0) { if (getArgs().get(0).equals(".")) { } else if (getArgs().get(0).equals("..")) { dir = dir.getParentFile(); } else { File paramDir = new File(getArgs().get(0)); if (paramDir.isAbsolute()) dir = new File(paramDir.getAbsolutePath()); else dir = new File(dir.getAbsolutePath() + System.getProperty("file.separator") + getArgs().get(0)); } } // Ensure the listed directory does exist if (dir == null || !dir.exists()) { try { this.getErrOut().write( ("ls: " + (dir == null ? "Can't find parent directory for " + getParentCurrentPath() : dir.getAbsolutePath() + " doesn't exist") + "\n").getBytes()); this.getErrOut().flush(); } catch (IOException e) { e.printStackTrace(); } } else try { for (File file : dir.listFiles()) { if (file.isDirectory()) out.write("[" + file.getName() + "]"); else out.write(file.getName()); out.newLine(); out.flush(); if (isInterrupted()) break; } } catch (IOException ioe) { ioe.printStackTrace(); throw new AppException("I/O operation error\n" + ioe.getMessage(), ioe); } catch (Exception e) { e.printStackTrace(); throw new AppException("Unexpected error\n" + e.getMessage(), e); } } /** * Provides help for users. * */ public String getHelp() { return "\n\nDescription:\n Lists the given directory\n\nUsage:\n" + "ls [dir]\n\n" + "dir\tDirectory to be listed ('.', '..', relative path, absolute path). " + "If this argument isn't used, the current directory is listed."; } }