I implemented a simple version of echo(1) command utility. The program works as described in the man page: it writes to the standard output all command line arguments, separated by a whitespace and end with a newline. It can process the option -n
that avoid to print the newline.
About my implementation, it is not complete, because it doesn't interpret common backslash-escaped characters (for example \n
, \c
, and so forth). i used a StringBuilder
object to build the output string, because I'm not sure that the standard output is buffered. I also make some checks so the program can work without specifying any arguments.
You can compile the program with javac JEcho
and run it with java JEcho <...>
.
JEcho.java
/**
* JEcho writes any command line argument to the standard output; each argument
* is separated by a single whitespace and end with a newline (you can
* specify '-n' to suppress the newline).
*
* This program doesn't interpret common backslash-escaped characters (for
* exampe '\n' or '\c').
*/
public class JEcho {
public static void main(String[] args) {
boolean printNewline = true;
int posArgs = 0;
if (args.length > 0 && args[0].equals("-n")) {
printNewline = false;
posArgs = 1;
}
StringBuilder outputBuilder = new StringBuilder();
for (; posArgs < args.length; posArgs++) {
outputBuilder.append(args[posArgs]);
outputBuilder.append(" "); // Separator.
}
// Remove the trailing whitespace at the end.
int outputLength = outputBuilder.length();
if (outputLength > 0)
outputBuilder.deleteCharAt(outputBuilder.length() - 1);
String output = outputBuilder.toString();
if (printNewline)
System.out.println(output);
else
System.out.print(output);
}
}