Monday, 17th October 2011
Follow WikiJava on twitter now. @Wikijava

SelectRows.java

From WikiJava

Jump to: navigation, search
The author suggests:

buy this book

SelectRows.java reads a file from the disk and outputs on standard output the lines in the file containing the given string. It is basically a very simple implementation of grep.

This Program can be executed by

java SelectRows <string> <filename>


Contents

the article

Select Rows opens a file for reading using java.io.bufferedReader:

bufferedReader = new BufferedReader(new FileReader(file));

then goes through all the lines of the file:

while ((cur = bufferedReader.readLine()) != null) {

and prompts them if they contain the string.

if (cur.contains(string))
    System.out.println(cur.trim());


Image:250px-Subversion.png
You can download the complete code of this article from the Subversion repository at this link

Using the username:readonly and password: readonly

See the using the SVN repository instructions page for more help about this.

SelectRows.java

package com.wikijava.files.manager;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
 
/**
 * @author Giulio
 * 
 */
public class SelectRows {
 
    /**
     * @param args
     */
    public static void main(String[] args) {
	if (args.length != 2) {
	    System.out.println("usage: java -jar SelectRows \"string\" file");
	    return;
	}
 
	File file = new File(args[1]);
	String string = args[0];
 
	BufferedReader bufferedReader = null;
	try {
	    bufferedReader = new BufferedReader(new FileReader(file));
	    String cur = null;
	    while ((cur = bufferedReader.readLine()) != null) {
		if (cur.contains(string))
		    System.out.println(cur.trim());
	    }
 
	    bufferedReader.close();
	} catch (IOException e) {
	    e.printStackTrace();
	}
 
    }
}




See Also

Copy of a File Tutorial, FileToString.java

Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page


Comments on wikijava are disabled now, cause excessive spam.