Hi my program needs to print a text file onto the terminal one line at a time. For example if I type, "java HT head -n 7 blablah.txt" it'll print the first 7 lines and if i type "java HT head -n 3 asdf.txt" itll print the first 3 lines of the txt file.
This is the code i have to print a txt file on the terminal one line at a time:
public static void printTextFile (String filename) throws IOException
{
FileInputStream fis = new FileInputStream(filename);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader (isr);
while (true) {
String line = br.readLine();
if (line == null) break;
System.out.println(line);
}
}
And this is my code that counts the number of lines:
public static int countLines (String filename) throws IOException
{
FileInputStream fis = new FileInputStream(filename);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader (isr);
int nlines;
for (nlines = 0; br.readLine() != null; nlines++);
return nlines;
}
I'm having trouble on how to combine the two to print the number of lines specified after the -n. Thanks for your help