I'm writting a grep-alike Java application which will take a string pattern as a first command line argument, and a list of files as the rest of arguments. Application will search every file. When the string is found, the application will print the file name, the line number and the entire content of the line where the string was found, like this:
filename - linenumber: content of line where the searched string was found
The code below works fine, but I need to implement threads, and synchronize them. Every file search need to be done in a separate thread and the result needs to be printed in the order of the given files on the command line.
Invocation should be like this: java Grep abc File1 File2 File3
And the output could look like this:
File1 - 28: xxxabcxxxxxxxxxxxx
File2 - 2: xxxxxxxxxxxxxxxxxxabcxxxxx
x
File2 -234: xxxxxxxxxabcx
File3 - 24: abcxxxxxxxxxxxxxxxxxx
My problem is that the files are not diplayed in the order they are given.
Every time I run it I get different order.
Can somebody explain me how to synchronize these threads?
A sample code would be great.
Thank you in advace.
////// here is my code //////
import java.io.*;
import java.util.*;
public class Grep1 extends Thread {
public String pattern;
public String fileName;
public Grep1( String threadName ){
super( threadName );
}
public void run(){
FileInputStream in;
try {
in = new FileInputStream( fileName );
grep( pattern, in, fileName );
in.close();
}
catch ( IOException e ) {
System.out.println( "Error: file " + fileName + " not found" );
}
}
public synchronized void grep( String pattern, FileInputStream in,
String file )
throws IOException{
boolean found = false;
int lineNumber = 0;
PrintStream out = System.out;
BufferedReader data = new BufferedReader( new InputStreamReader(in) );
LineNumberReader infile = new LineNumberReader( data );
String line = infile.readLine();
while ( line != null ) {
if ( line.indexOf(pattern) >= 0 ){
lineNumber = infile.getLineNumber();
out.println( file + " - " + lineNumber + ": " + line );
found = true;
}
line = infile.readLine();
}
if( found == false )
out.println( "Couldn't find \"" + pattern + "\" in " + file );
}
public static void main( String[] args ){
int numOfArgs = args.length;
if ( numOfArgs < 2 ) {
System.err.println( "Usage: java Grep [pattern] file1 file2 ...");
return;
}
else{
Grep1[] g = new Grep1[ numOfArgs-1 ];
for ( int i=0; i<g.length; i++ ){
g[i] = new Grep1( args[i+1] );
g[i].pattern = args[0];
g[i].fileName = args[i+1];
g[i].start();
}
}
}
}
/////// the end /////////