HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Get the first 10 lines of a file

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
filethegetfirstlines

Problem

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);
            }
        }
    }
}

Solution

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);
    }

}

Code Snippets

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);
    }

}

Context

StackExchange Code Review Q#79024, answer score: 7

Revisions (0)

No revisions yet.