Java line numbers and text files

I am studying my final, and I am wondering if there is a way to print the string data in a text file. for example, if the following was in the text file:

11 
1c20 
203 
G2 

I was wondering if there is an input method, for example, 2, 4, I would get the output 1c20 203 G2. using two integer beginning and end. I have research for this method, but I can not find anything. I understand that there is getLineNumber (), but I want to use two integers.

Thanks in advance!

+3
source share
3 answers

Here's the option (with pointers):

+3

, java.io.LineNumberReader: http://docs.oracle.com/javase/6/docs/api/java/io/LineNumberReader.html

, 0

:

import java.io.*;

/*
 * Usage: java LinePrinter <start> <end>
 * Example: java LinePrinter 2 4
 */
public class LinePrinter
{
    public static void main(String[] args)
    {
        int start = Integer.parseInt(args[0]);
        int end = Integer.parseInt(args[1]);

        LineNumberReader reader = null;
        String line = null;
        boolean flag = false;

        try
        {
            reader = new LineNumberReader(new FileReader("data.txt"));

            while ((line = reader.readLine()) != null)
            {
                if (reader.getLineNumber() == start)
                {
                    flag = true;
                }

                if (flag)
                {
                    System.out.println(line);
                }

                if (reader.getLineNumber() == end)
                {
                    flag = false;
                    break;
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}
+2

Assuming your file is named data.txt, you can use sed to display lines 3 through 5 as follows:

$> sed -n '3,5p' data.txt

0
source

All Articles