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!
Here's an option (with pointers):
start and endBufferedReader#readLine, increase the counter for each lineend, break from the loop.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();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With