Write a program Find that searches all files specified on the command line and p
ID: 3870776 • Letter: W
Question
Write a program Find that searches all files specified on the command line and prints out all lines containing a specified word. For example, if you call
java Find ring report.txt addres.txt Homework.java
then the program might print
The specified word is always the first command line argument.
Here is an example of a txt that could be used, Mary.txt
Mary had a little lamb,
little lamb, little lamb,
Mary had a little lamb, its fleece was white as snow.
And everywhere that Mary went,
Mary went, Mary went,
and everywhere that Mary went, the lamb was sure to go.
It followed her to school one day
school one day, school one day,
It followed her to school one day, which was against the rules.
It made the children laugh and play,
laugh and play, laugh and play,
it made the children laugh and play to see a lamb at school.
Explanation / Answer
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
class FindWord{
private String word;//word to be find
FindWord(){word = null;}//Default constructor
FindWord(String word)//Parametric constructor
{
this.word = word;//Initializing the word with required word
}
void print_line(String file_name)//function to find the line with word and print
{
System.out.println("file_name:"+file_name);
try{
File file = new File(file_name);
FileReader reader = new FileReader(file);
BufferedReader buffer = new BufferedReader(reader);
String line;
while((line = buffer.readLine())!=null)//Reading the file line by line
{
if(line.contains(word))//Checking whether line contains word
{
System.out.println(line);//Printing the line if the word presents
}
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
class Find{
public static void main(String[] args)
{
if(args.length == 0)
{
System.out.println("No arguments provided....");
return;
}
String word = args[0];
FindWord findword = new FindWord(word);//creating object with required word as parameter
for(String arg:args)//iterating each file
{
if(arg == word)
continue;
else
findword.print_line(arg);//calling the function to find the lines with word
}
return;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.