Exemplo n.º 1
0
  /**
   * Move file or directory oldFile to newFile;
   *
   * @param oldFile a full path to a JShellItem or the name of a JShellItem in the current directory
   *     which needs to be moved.
   * @param newFile a full path to a directory or the name of a directory in the current directory
   *     to which oldFile needs to be moved.
   */
  public void mv(String oldFile, String newFile) throws Exception {
    JShellItem source = getItemAtPath(oldFile, 0);
    if (source == null) {
      throw new Exception(oldFile + ": doesn't exist.");
    }
    Directory sourceParent = source.getParentDirectory();
    Directory destinationParent;
    String newName;

    if (newFile.endsWith("/")) {
      destinationParent = (Directory) getItemAtPath(newFile, 0);
      newName = source.getName();

    } else {
      destinationParent = (Directory) getItemAtPath(newFile, 1);
      newName = newFile.substring(newFile.lastIndexOf("/") + 1);
    }

    if (destinationParent == null) {
      throw new Exception(newFile + ": invalid destination path.");
    }
    if (destinationParent.contains(newName)) {
      throw new Exception(newFile + ": already exists.");
    }
    sourceParent.removeItem(source);
    source.setName(newName);
    if (source instanceof Directory) {
      if (destinationParent.isChildOf((Directory) source)) {
        throw new Exception(
            String.format(
                "mv: cannot move '%s' to a subdirectory of itself, '%s'", oldFile, newFile));
      }
      newName.concat("/");
    }
    source.setPath(destinationParent.getPath() + newName);
    source.setParentDirectory(destinationParent);
    destinationParent.addItem(source);
  }