Java Runtime Issue / Text File Searching

R

rajatag

Hi folks,

Here's a tricky one (I think):

I need to search for words within a file. To do this, I thought of
using grep and executing from Runtime.getRuntime() instead of writing
something in Java.

Now, when I run the following in linux:

grep -c -x -F 'HOT' filetosearch.txt

The program prints out 1 which is correct as the file specified above
has just one occurrence of the word HOT on a single line. However, when
I put the same thing within Java like this:

Runtime rt = Runtime.getRuntime();
Process pt = rt.exec("grep -c -x -F 'HOT' filetosearch.txt");

Then the Java application always gets a 0 count.

Any ideas why? Also, is there any better way to do searching of text
files within java?
 
G

Gordon Beaton

Runtime rt = Runtime.getRuntime();
Process pt = rt.exec("grep -c -x -F 'HOT' filetosearch.txt");

Then the Java application always gets a 0 count.

Any ideas why? Also, is there any better way to do searching of text
files within java?

When you run the command from a shell, it removes the single quotes
from the search string and they aren't ever seen by grep.

When you run the command from Java, there is no shell and grep is
looking for the 5-characters 'HOT' (i.e. including the 2 single
quotes), which presumably isn't in your file.

/gordon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top