Sunday, 15 May 2011

The mystery of the whitespace

Recently I had to write a program which taked a printer name as a command line parameter and spools the file to this printer.

Printer name if "Hp Office  5200". As you can see there are 2 whitespaces between "Office" and "5200". Well, I didn't manage to print. I got all the time "Invalid Printer Name"

exception. Finally I noticed that double whitespace is trancated to single whitespace. I made a research on the net and it appears to be that putting the string into double quots should

preserve the string. Well, it is not. I run some tests on Unix and Window


X=`echo Hello From        Michael` echo $X Output: Hello From Michael X=`echo "Hello From       Michael"` echo $X Output: Hello From Michael

So double whitespace dissapeaded in both cases. Now on Windows Platform

set X="Hello   From    Michael"  echo %X%

Output: Hello  From  Michael.    Double whitespace preserved!!!!!!

So I decided to write small Java class that executes "Windows" command line command

public class CmdExec { public static void main(String argv[]) {
try {
String line;
String str
= "cmd /c echo "+argv[0];
Process p
= Runtime.getRuntime().exec(str);
BufferedReader input
new BufferedReader
new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
catch (Exception err) {

java  CmdExec "Hello  From  Michael"

Output : Hello From Michael. Double whitespace dissapeared!!!!!

This explains the strange thing with Printer Name.

I had to say, that till now I didn't find a way to pass the printer name in the safe way

No comments:

Post a Comment