File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Running Windows cmd findstr within java app Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Running Windows cmd findstr within java app" Watch "Running Windows cmd findstr within java app" New topic

Running Windows cmd findstr within java app

David Huynh

Joined: Jun 05, 2011
Posts: 2
Hi everybody,

I'd like to use findstr to see if a string exists or not within one or multiple directories. I found that for example findstr /c:\"word\" /d:C:\test;C:\test1 *.txt works fine within command prompt (given folders are made and whatnot), but I was wondering how I could implement this within a java method in order to run this command within an app, then do whatever depending on the output returned. From my google search, I tried the following:

What I was given back in the console was "C::" I'm not exactly sure what this means, but like I said the command does work in command prompt so I was expecting the same return value. I have also tried using process builder in order to do this, but as expected it gave me the same output.

Perhaps I did something wrong for the param of the exec method? Really unsure. Any help would be appreciated.

Joanne Neal

Joined: Aug 05, 2005
Posts: 3742
\ is a special character in Java strings which is used to escape other characaters - one of the characters it can be used to escape is a 't', \t in a Java string actually represenst a tab
" is also a special character (it marks the beginning and end of of a string literal - if you want an actual " in your string you need to escape it with a \.
So the actual command you are running is
findstr /c"word" /d:C:<tab>est;C:<tab>est1 *.txt
which is probably why you are getting strange results.

Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

I would advise you to read this article. Is a bit old but still very relevant.

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
David Huynh

Joined: Jun 05, 2011
Posts: 2
Ah, I see what I did wrong now. Working nicely now, thanks a lot. Will also take a look at the article.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46362
. . . and welcome to the Ranch
I agree. Here's the link:
subject: Running Windows cmd findstr within java app
It's not a secret anymore!