[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 334
  • Last Modified:

Windows path from cmd Line replace \ by \\

Hello ...
I am getting the directory path (complete path) from the command line.I am using this path as a parameter to a perl script that I run through my Java application (Java Process).Due to some reason I am unable to run the application through  Java .I suspect that since this is in Windows ...and I guess java expects teh paths to be in --"c:\\perl\\bin\\dir" and not "c:\perl\bin\dir"...that this might be the problem.

I tried replacing \ with \\..but the IDE does not allow me to do this ..

ompPath=compPath.replaceAll("\","\\");

How do I replace the single \ with a double \\

Thanks for your time.
0
micro_learner
Asked:
micro_learner
  • 4
  • 4
  • 2
  • +7
3 Solutions
 
vijaydograCommented:
try
ompPath=compPath.replaceAll("\\\\","\\\\");
0
 
kupra1Commented:
or you can use this too:
ompPath=compPath.replaceAll("\\","/");
0
 
micro_learnerAuthor Commented:
Hello Kupra ...The above gives an error ..

Exception in thread "main" java.util.regex.PatternSyntaxException:
ternal error near index 1
\
 ^
        at java.util.regex.Pattern.error(Pattern.java:1650)
        at java.util.regex.Pattern.compile(Pattern.java:1403)
        at java.util.regex.Pattern.<init>(Pattern.java:1124)
        at java.util.regex.Pattern.compile(Pattern.java:817)
        at java.lang.String.replaceAll(String.java:2000)
        at micropipe.PipeLineMA.cmdCheckEXP(PipeLineMA.java:389)

########################
Vijay ...u'rs does not work too ..am I missing something ...thanks
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
vijaydograCommented:
Sorry I forgot again....
I have been told by CEHJ before also

try this
ompPath=compPath.replaceAll("\\\\","\\\\\\\\");

both parameters are regex as input. :D
sorry for mistake
0
 
aozarovCommented:
I think you need to do: compPath.replaceAll("\\", "\\\\")
0
 
micro_learnerAuthor Commented:
Thank you Vijay ..what you said works ...but I dont seem to get the process running form java application.

The situation is this.

1.I get the input dir from the command Line  say .. C:\data
2.I convert it into a string comPath=arg[1]
3.Replace the \ b y \\
4.Run the application by using Java Process ...

It does not run .,..though the euivalant runs just fine on the cmd Line ...

Thanks for your time
0
 
vijaydograCommented:
if you are trying to run a process by changing the directory and then giving the command then u have to do that in one process statement:
like
Process ls_proc = Runtime.getRuntime().exec("cmd /C cd "+" PATH_OF_EXE  " + " && NAME_OF_EXE FILE ");
and then to see the result you can put that in file or system console using

                      InputStream is = ls_proc.getErrorStream();
                  InputStreamReader isr = new InputStreamReader(is);
                  BufferedReader br = new BufferedReader(isr);
                  String line=null;
                  while ( (line = br.readLine()) != null)
                  {
                          System.out.println(">>"+line);
                  }      
                  
Hope this helps!!!
0
 
aozarovCommented:
>> compPath.replaceAll("\\\\","\\\\\\\\");
I can accept that it works but I don't understand why based on the Javadoc
From the Javadoc:
http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html
The backslash character ('\') serves to introduce escaped constructs, as defined in the table above, as well as to quote characters that otherwise would be interpreted as unescaped constructs. Thus the expression \\ matches a single backslash and \{ matches a left brace.

Also,
Runtime.getRuntime().exec("cmd /C cd "+" PATH_OF_EXE  " + " && NAME_OF_EXE FILE ");
can be changed to a more standard way using
Runtime.getRuntime().exec("cmd /C " + NAME_OF_EXE FILE, null, new java.io.File(PATH_OF_EXE));

based on: http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html#exec(java.lang.String,%20java.lang.String[],%20java.io.File)
0
 
vijaydograCommented:
To aozarov
According to replaceAll method of String class it takes two parameters first one as regex and other as simple parameter.
But (even I was surprised when I realized) that is wrong. Both parameters are regex.
And yes the process can be done that way also rather it seems more clean than mine :).
0
 
NaeemgCommented:
hello, try this code, it will replace single back slashes with double,

    char BACK_SLASH = '\\';

    String str = "c:\\perl\\bin\\dir"; //-- don't worry doubly back slash is used as single in java here.
    StringBuffer sb = new StringBuffer(str);
    System.out.println(sb.toString());
    System.out.println(sb.length());

    for(int i = 0; i < sb.length(); i++)
    {
      //System.out.println(sb.charAt(i));
      if(sb.charAt(i) == BACK_SLASH)
      {
        //str = str.substring(0, i) + BACK_SLASH + str.substring(i + 1, str.length());
        sb.insert(i+1, BACK_SLASH);
        //System.out.println(sb.toString());
        sb.setLength(sb.length());
        i++;
      }
    }
    System.out.println(sb.toString()); // your out put will cotains strings with double slash,
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Its safest to replace all occurances of \ or \\ with /. It would work on all platforms.

compPath = compPath.replaceAll ( "\\\\","/" ) ; // replace all \\ with /
compPath = compPath.replaceAll ( "\\","/" ) ; // replace all \ (if there are any single slashes by mistake) with /

0
 
mightyoneCommented:
back to the prob

you must have a line of code similar to this

String cmd = ....

Runtime.getRuntime().exec(cmd);

add a   "  >  test.txt" to cmd so it does not execute it but writes it to a file called test.txt


afterwards search for the file to make sure your perl call is on right path and then display the file to see the command given to the console.

btw.   even on windows i suggest to use "/" if you do not want to use File.separator !!!
e.g.

compPath.replaceAll("\\\\",File.separator);

MoghtyOne
0
 
CEHJCommented:
>>
I have been told by CEHJ before also

try this
ompPath=compPath.replaceAll("\\\\","\\\\\\\\");
>>

Your memory hasn't failed you ;-) I'm content to think of the explanation as being that the character needs escaping once as it's a Java escape character and once more as it's a regex escape character
0
 
MogalManicCommented:
The double backslash is confusing the issue.  \\ is ONLY used inside Java.  When specifying paths in Windows, you need to use \ only.

Your best bet is to use java.io.File objects and verify that ALL of the files you need exist BEFORE calling the script.  Maybe something like this:
public void ExecutePerlScript(String dir, String script) throws IOException
{
      String[] envp = null;
      File workingDir=new File("c:\\perl\\bin\\dir");
      File perlCmd=new File(workingDir, "perl.exe");
      File commandFile=new File(dir, script);
      if (workingDir.exists()==false || perlCmd.exists()==false)
            throw new FileNotFoundException("Perl is not correctly installed at "+workingDir);

      if (commandFile.exists()==false)
            throw new FileNotFoundException("Missing perl script file"+commandFile);
                  
      String command=perlCmd.getAbsolutePath()+" "+commandFile;
      Process cmd=Runtime.getRuntime().exec(command, envp, workingDir);
      BufferedReader results=new BufferedReader(new InputStreamReader(cmd.getInputStream()));
      
      String line;
      while ((line=results.readLine())!=null) {
            System.out.println(line);
      }
}
0
 
objectsCommented:
> 2.I convert it into a string comPath=arg[1]
> 3.Replace the \ b y \\

I'm not sure you actually need to convert them at all you're getting the string from the command line.
The problem sounds like it is elsewhere.

The following gives an example of running exec() and reading the output (required so full buffers don't block the process).

http://www.objects.com.au/java/examples/util/ConsoleExec.do


0
 
micro_learnerAuthor Commented:
thanks all ..
0
 
CEHJCommented:
:-)
0
 
mightyoneCommented:
Hoho, no one read the advice using File.separator instead of escaping \ .....

that is no platform independency I would like to buy :-(
0
 
micro_learnerAuthor Commented:
I am sorry MightOne ...but Thanks for your help.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 4
  • 4
  • 2
  • +7
Tackle projects and never again get stuck behind a technical roadblock.
Join Now