Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Line numbers and text files Java

Tags:

java

I'm studying for my finals and i wondering if there is a particular way of printing out the data of a line in a text file. for example if i had the following in a text file:

11 
1c20 
203 
G2 

I was wondering if there is a way where I input for example 2 ,4 i would get an output 1c20 203 G2. by using two integers start and finish. i have research for this method, but unable to find anything. I understand there is a is a getLineNumber() but i want to use the two Integers.

Thanks in advance!

like image 418
Pro-grammer Avatar asked Aug 12 '26 18:08

Pro-grammer


2 Answers

Here's an option (with pointers):

  1. Read the inputs and store them in a two variables start and end
  2. Read each line using BufferedReader#readLine, increase the counter for each line
  3. If the line number is in the range, print the line.
  4. When counter reaches end, break from the loop.
like image 84
MByD Avatar answered Aug 15 '26 08:08

MByD


You might want to take a look at java.io.LineNumberReader: http://docs.oracle.com/javase/6/docs/api/java/io/LineNumberReader.html

Note that line numbers start at 0

Try this:

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();
        }
    }
}
like image 36
cadizm Avatar answered Aug 15 '26 08:08

cadizm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!