But my request is that "Is there any java method which can work like grep command in unix"
My requirement is - I have to search a text string in a file which is present in unix system.
I am writing a java class in my windows os whose aim is to connect to the unix server and search the text in that file.
Now I am able to connect the unix server using a java class com.jcraft.jsch.ChannelSftp and go to that directory where that file exist and get the whole file to my java program.The methods are cd and get in ChannelSftp.
But this approach will be taking time as I have to search this file through java program.
But If I am able to use the grep command using java program , then I can pull only the required text which will be more effective.
Java itself doesn't have one single method like grep. You would really need to read the file line by line, and use Pattern on each separate line. It will be faster if you create the Pattern outside the loop.
You can call grep itself from Java using Runtime.exec() or ProcessBuilder. However, I doubt that this will be faster, as the JVM needs to spawn a new process for that.
siddharth das wrote:But If I am able to use the grep command using java program , then I can pull only the required text which will be more effective.
Another thing you might want to consider is to split the operations up completely and run them in a script instead. Then you could pipe the output of your sftp command directly to a grep, and the result of that to your java program. You wouldn't have to worry about any of that com.jcraft.jsch.ChannelSftp stuff, and your program could concentrate on what it is (presumably) supposed to do: parse the output of the grep.
Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here