示例#1
0
  /**
   * If there's an operator and filename in the list of parameters, then if operator is '>',
   * overwrites the contents of outFile with the string text; if the operator is '>>', appends text
   * to the contents of outFile; If outFile doesn't exist, creates a new file outFile and appends
   * text to its contents.
   *
   * @param params A list of parameters which must include a string and may optionally include an
   *     operator and a filename.
   */
  public String echo(List<String> params) throws Exception {
    // The content to be output in retrieved
    String content = getContent(params);
    // The last index of the string, if it exists, in the List params.
    int last_index = getLastIndex(params);
    // If content is a valid string and the correct syntax is used to write
    // to a file, then this code is executed.
    if (params.size() > last_index + 2
        && content.startsWith("\"")
        && content.endsWith("\"")
        && content.startsWith("\"")
        && params.get(last_index + 1).startsWith(">")) {

      // The file name and parameter for writing is retrieved.
      String file_name = params.get(last_index + 2);
      String param = params.get(last_index + 1);
      // The quotations are striped from the string to be used.
      content = content.substring(1, content.length() - 1);

      // The file is retrieved if it exists.
      JShellItem targetFile = getItemAtPath(file_name, 0);

      // The file is deleted if it exists and is to be overwritten.
      // Otherwise the file is created.
      if (!(param.equals(">>") & targetFile != null)) {
        if (targetFile != null) {
          targetFile.getParentDirectory().removeItem(targetFile);
        }
        mkfile(file_name);
        targetFile = getItemAtPath(file_name, 0);
      }

      // The file's contents are appended to either a blank (new) file
      // or an old file, depending on the user's input.
      ((File) targetFile).setContent(((File) targetFile).getContent() + content);

      return "";
      // If the string is valid but the syntax is incorrect, then this
      // code is
      // executed.
    } else if (content.endsWith("\"") & content.startsWith("\"")) {
      if (content.substring(1, content.length() - 1).isEmpty()) {
        return content.substring(1, content.length() - 1);
      }
      return content.substring(1, content.length() - 1) + "\n";
      // If the string is not valid, this code is executed.
    } else {
      return "Echo requires a string with \" & \" surrounding the words" + "\n";
    }
  }