get First Line from a text file - Java java.io

Java examples for java.io:File Extension Name

Description

get First Line from a text file

Demo Code

// Licensed under the Apache License, Version 2.0 (the "License");
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import org.apache.log4j.Logger;

public class Main{
    public static void main(String[] argv) throws Exception{
        File file = new File("Main.java");
        System.out.println(getFirstLine(file));
    }//w ww. j av a  2  s  .  co m
    private static Logger logger = Logger.getLogger(FileReadHelper.class);
    public static String getFirstLine(File file) {
        try {
            BufferedReader reader = new BufferedReader(
                    new FileReader(file), 1024);
            String line = reader.readLine();
            reader.close();
            return (line != null) ? line : "";
        } catch (IOException ex) {
            logger.warn(
                    String.format(
                            "Failed to read contents from file %s. Returning a default empty string.",
                            file.toString()), ex);
            return "";
        }
    }
}

Related Tutorials