0

i am having text file called "Sample.text". It contains multiple lines. From this file, i have search particular string.If staring matches or found in that file, i need to print entire line . searching string is in in middle of the line . also i am using string buffer to append the string after reading the string from text file.Also text file is too large size.so i dont want to iterate line by line. How to do this

santro
  • 373
  • 1
  • 6
  • 22

2 Answers2

6

You could do it with FileUtils from Apache Commons IO

Small sample:

    StringBuffer myStringBuffer = new StringBuffer();
    List lines = FileUtils.readLines(new File("/tmp/myFile.txt"), "UTF-8");
    for (Object line : lines) {
        if (String.valueOf(line).contains("something")) { 
            myStringBuffer.append(String.valueOf(line));
        }
    }
Francisco Spaeth
  • 23,493
  • 7
  • 67
  • 106
  • thanks for your reply . searching string is in in middle of the line . also i am using string buffer to append the string after reading the string from text file.Also text file is too large size.so i dont want to iterate line by line. – santro Jun 23 '12 at 11:56
  • From the question I suspect he wants to know if the string is contained in the line. Maybe you want to switch `startsWith` with `contains`. – atamanroman Jun 23 '12 at 11:56
1

we can also use regex for string or pattern matching from a file.

Sample code:

import java.util.regex.*;
import java.io.*;

/**
 * Print all the strings that match a given pattern from a file.
 */
public class ReaderIter {
  public static void main(String[] args) throws IOException {
    // The RE pattern
    Pattern patt = Pattern.compile("[A-Za-z][a-z]+");
    // A FileReader (see the I/O chapter)
    BufferedReader r = new BufferedReader(new FileReader("file.txt"));
    // For each line of input, try matching in it.
    String line;
    while ((line = r.readLine()) != null) {
      // For each match in the line, extract and print it.
      Matcher m = patt.matcher(line);
      while (m.find()) {
        // Simplest method:
        // System.out.println(m.group(0));
        // Get the starting position of the text
        int start = m.start(0);
        // Get ending position
        int end = m.end(0);
        // Print whatever matched.
        // Use CharacterIterator.substring(offset, end);
        System.out.println(line.substring(start, end));
      }
    }
  }
}
Umer
  • 1,098
  • 13
  • 31