Skip to content

Instantly share code, notes, and snippets.

@electrocucaracha
Created April 9, 2014 14:07
Show Gist options
  • Save electrocucaracha/10274622 to your computer and use it in GitHub Desktop.
Save electrocucaracha/10274622 to your computer and use it in GitHub Desktop.
Write a Java program that takes a list of filenames on the command line and prints out the number of lines in each file. The program should create one thread for each file and use these threads to count the lines in all the files at the same time. Use java.io.LineNumberReader to help you count lines. You'll probably want to define a LineCounter …
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
public class LineCounter extends Thread {
private static final String FOLDER_PATH = "C:\\temp";
private File file;
public void run() {
FileReader fr = null;
try {
fr = new FileReader(file);
} catch (Exception e) {
e.printStackTrace();
}
if (fr != null) {
LineNumberReader lnr = new LineNumberReader(fr);
try {
lnr.skip(Long.MAX_VALUE);
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println(file.getName() + " " + lnr.getLineNumber());
}
}
public LineCounter(File file) {
super();
this.file = file;
}
public static void main(String... args) {
long start = System.currentTimeMillis();
File folder = new File(FOLDER_PATH);
LineCounter lc;
for (File file : folder.listFiles()) {
if (file.isFile()) {
lc = new LineCounter(file);
lc.start();
// lc.run();
}
}
System.out.println("Lapse = " + (System.currentTimeMillis() - start)
+ " miliseconds");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment