Thursday, 24th June 2010
The new frontier for learning Java

AddLineNumbers.java

From WikiJava

Jump to: navigation, search
The author suggests:

buy this book

This simple program adds line numbers to the rows of any file. printing them in the standard output.

It can be useful when you need to paste source code on a website (for example on WikiJava) with line numbers.

Contents

the article

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.

The code is very straight forward:

  1. it opens all the files passed in input at command line (wild cards are accepted too).
  2. Reads the files line per line
  3. prints each line including the line number.
  4. closes each stream to the file.

AddLineNumbers.java

package org.wikijava.files;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
 
/**
 * @author giulio
 * 
 */
public class AddLineNumbers {
 
    /**
     * @param args
     */
    public static void main(String[] args) {
	if (args.length < 1) {
	    System.out.println("usage: java -jar AddLineNumbers [file]+");
	    return;
	}
 
	File[] files = new File[args.length];
	for (int i = 0; i < args.length; i++) {
	    files[i] = new File(args[i]);
	}
 
	for (int i = 0; i < files.length; i++) {
	    if (files[i].isFile()) {
		try {
		    BufferedReader bufferedReader = new BufferedReader(
			    new FileReader(files[i]));
		    String cur = null;
		    long count = 1;
		    while ((cur = bufferedReader.readLine()) != null) {
 
			System.out.println(count + " " + cur);
			count++;
		    }
 
		    bufferedReader.close();
		} catch (IOException e) {
		    // TODO Auto-generated catch block
		    e.printStackTrace();
		}
	    }
	}
 
    }
 
}

See Also

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


Title (required):

Website:

Comment: