We are suppose to create a method that • The number of lines in the file • The number of words in the file, and • The number of characters in the file excluding blanks. i.e File: xxx.txt has 120 lines, 317 words, 4154 characters
• Search the file line by line for a given string. The output must contain the line number followed by the contents of the line that contains the search argument. For instance given the following as input string: Java, where Java is the search string the output would be something like this:
5: on the island of Java
9: The people of JAVA loves jaVa.
Use the class LineNumberReader for this exercise
I am having a difficult time. I keep getting an I/O error saying stream closed when I am running my code.
This is my code. I have the part of lines, words, characters. But I can't get the second part to work
public String wordCount()
{
try
{
int wordCount = 0,
numberCount = 0,
lineCount = 1,
characterCount = 0;
String c = " ";
FileReader r = new FileReader(f);
LineNumberReader lnr = new LineNumberReader(r);
StreamTokenizer t = new StreamTokenizer(r);
ArrayList <String> results = new ArrayList<String>();
t.resetSyntax();
t.whitespaceChars(0, ' ');
t.wordChars('a','z');
t.wordChars('A','Z');
t.wordChars('0','9');
t.eolIsSignificant(true);
while(t.nextToken() != StreamTokenizer.TT_EOF)
{
switch(t.ttype)
{
case StreamTokenizer.TT_NUMBER:
numberCount++;
break;
case StreamTokenizer.TT_WORD:
characterCount += t.sval.length();
wordCount++;
break;
case StreamTokenizer.TT_EOL:
lineCount++;
break;
case StreamTokenizer.TT_EOF:
break;
default:
}
}
r.close();
BufferedReader bf = new BufferedReader(new FileReader(f));
BufferedWriter out = new BufferedWriter(new FileWriter("test.txt"));
BufferedWriter output = new BufferedWriter(new FileWriter("output.txt"));
int recCount = 0;
String record = null;
while ((record = bf.readLine()) != null) {
recCount++;
out.write(recCount + ": " + record);
out.newLine();
}
out.close();
String ask = "Enter Word";
String find = JOptionPane.showInputDialog(ask);
String word = find;
while(lnr.readLine() != null )
{
String line = lnr.readLine();
if (line.indexOf(word) >= 0)
{
results.add(lnr.getLineNumber() + line);
}
}
lnr.close();
String str = f.getName() + " has " + lineCount + " line(s), " +
wordCount + " word(s), " +
characterCount + " characters. " + "\n These lines contain"
+ "the word in search of:" ;
for(int index=0; index<results.size();index++)
{
if(results !=null)
{
str+= results.get(index) + "\n";
}
}
return str;
}
I notice it breaks around the this part of code. If I comment the code out it works minus the part I am trying to do.
String ask = "Enter Word";
String find = JOptionPane.showInputDialog(ask);
String word = find;
while(lnr.readLine() != null )
{
String line = lnr.readLine();
if (line.indexOf(word) >= 0)
{
results.add(lnr.getLineNumber() + line);
}
}
lnr.close();