get Line Beginning With from a File - Java File Path IO

Java examples for File Path IO:Text File

Description

get Line Beginning With from a 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");
        String value = "java2s.com";
        System.out.println(getLineBeginningWith(file,value));
    }// w ww.jav a 2 s. c om
    private static Logger logger = Logger.getLogger(FileReadHelper.class);
    public static String getLineBeginningWith(File file, String value) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));

            String line;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith(value)) {
                    break;
                }
            }

            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