JAVA: Write a program Find that searches all files specified on the command line
ID: 664385 • Letter: J
Question
JAVA:
Write a program Find that searches all files specified on the command line and prints out all lines containing a reserved word. Start a new thread for each file. For example, if you call
then the program might print
I'm not getting any output from my program:
import java.io.FileInputStream;
import java.util.Scanner;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.InterruptedIOException;
//P20.9 Find a target string in a file and print the line
public class FindRunnable implements Runnable
{
private String target;
private String fileName;
public FindRunnable(String aTarget, String aFileName)
{
target = aTarget;
fileName = aFileName;
} // end of constructor
public void run()
{
try
{
Scanner in = new Scanner(new FileInputStream(fileName));
while (in.hasNextLine())
{
String line = in.nextLine();
if ((line.indexOf(target)) != -1)
{
System.out.println(fileName + ": " + line);
}
} // end of while
} // end of try
catch (FileNotFoundException e)
{
System.out.println(fileName + " not found ");
}
catch (IOException e)
{
System.out.println(e);
}
} // end of run method
} // end of FindRunnable
CLASS: FIND
public class Find
{
public static void main(String[] argv)
{
for (int i = 1; i < argv.length; i++)
{
FindRunnable finder = new FindRunnable(argv[1], argv[i]);
Thread t = new Thread(finder);
t.start();
} // end of for loop
} // end of main
} // end of find classimport java.io.*;
java Find Buff report.txt address.txt Homework.java
Explanation / Answer
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.PrintWriter;
public class myfind {
public static boolean hasString(String Line,String Pattern){
boolean has=false;
String Temp;
for(int i=0;i<(Li
ne.length()
-
Pattern.length()+1);i++){
Temp=Line.substring(i, i+Pattern.length());
if(Temp.equals(Pattern)) {has=true;i=Line.length()
-
Pattern.length()+1;}
}
return has;
}
static public void main(String a
rg[]) throws java.io.IOException {
String Pattern = arg[0];
for (int nFile = 1; nFile < arg.length; nFile++) {
System.out.println("Processing " + arg[nFile] + "... ");
BufferedReader br = new BufferedReader(new FileReader(arg[nFile]));
String line = br.readLine();
if(hasString(line,Pattern)) System.out.println(arg[nFile]+ ": " + line);
while (line != null) {
line = br.readLine();
if(hasString(line,Pattern)) System.out.println(arg[nFile]+ ": " +
line);
}
br.close();
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.