• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1620
  • Last Modified:

how to find a string in file

i need to find a string in a file and print
each line of the file that the string in it.

how i should do it?

detailed code will be a great help

thanks
0
talsp
Asked:
talsp
1 Solution
 
blairdyeCommented:
Sorry about the formatting, just cut and paste.

import java.io.*;
import java.util.*;
public class OutputStringClass {
 String fileIn;
 private BufferedReader inputFile;
 public OutputStringClass(String fileIn) {
      super();
      this.fileIn = fileIn;
      try {
            inputFile = new BufferedReader(new FileReader(fileIn));
      } catch (Exception e) {
            System.out.println("Exception in OutputStringClass constructor" + e);
      }
 }
      
 public static void main(String[] args) {
      OutputStringClass outputStringClass = new OutputStringClass("c:/tmp/test.txt");
      outputStringClass.writeString("textstring");
 }
      
 public void writeString(String toWrite) {
      String line;
      try {
            while ((line = inputFile.readLine()) != null) {
                  StringTokenizer myTokenizer = new StringTokenizer(line);
                  while (myTokenizer.hasMoreTokens()) {
                        String nextToken = myTokenizer.nextToken();
                        if (nextToken.equals(toWrite)) {
                              System.out.println("line =" + line);
                        }
                  }
            }
      } catch (Exception e) {
        System.out.println("Error in writeString() " + e);
      }
 }
}

Blair
0

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now