6
\$\begingroup\$

Print the first 10 lines of a file, if it has less than 10 lines, print the whole file.

Any suggestions on any kind of improvement are welcome.

package je3.io;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * Created by IDEA on 29/01/15.
 */
public class Head {
    public static String[] headLines(String filename) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(filename));
        String[] lines = new String[10];
        String line;
        int nLine = 0;
        while((line = reader.readLine()) != null) {
            lines[nLine++] = line;
            if(nLine >= 10) {
                break;
            }
        }
        return lines;
    }

    public static void main(String[] args) throws IOException {
        if(args.length != 1) {
            throw new IllegalArgumentException();
        }
        String[] lines = headLines(args[0]);
        for(String line : lines) {
            if(!line.isEmpty()) {
                System.out.println(line);
            }
        }
    }
}
\$\endgroup\$
7
\$\begingroup\$

This code is just begging for a Java8 implementation.... and, given that Java 8 has been available for almost a year, it seems reasonable.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;


public class Head {

    public static void main(String[] args) throws IOException {
        if (args.length != 1) {
            throw new IllegalArgumentException();
        }

        Files.lines(Paths.get(args[0])).limit(10).forEach(System.out::println);
    }

}
\$\endgroup\$
  • \$\begingroup\$ Out of curiosity, does that only read 10 lines (on demand) or the whole file (filter)? \$\endgroup\$ – Jack Jan 30 '15 at 1:43
  • \$\begingroup\$ Only the first 10 lines (with perhaps a small amount of overread...). \$\endgroup\$ – rolfl Jan 30 '15 at 2:29
  • 1
    \$\begingroup\$ A little cleaner, in my opinion, is to replace your lambda with a method reference: .forEach(System.out::println). \$\endgroup\$ – wchargin Jan 30 '15 at 3:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.