Organizational Research By

Surprising Reserch Topic

Java: How to read a specific line from a text file?


I have this text file:

2013001  Jaymarion Manalo L. Service Crew March 15, 2013   8:00   12:00   13:00   17:00   10.0
2013001  Jaymarion Manalo L. Service Crew March 16, 2013   8:00   12:05   13:05   17:30   10.0

Now, I have a condition that if String date1 = "March 15, 2013", it will read the line where it belongs and will only get the "8:00", "12:00", "13:00", and "17:00" and display it on the text fields I have declared. I mean, is that even possible? How is it done? I hope you're getting what I'm trying to say. I am so new at Java -_-

 


asked Jun 18, 2015 in Core java by rajesh
0 votes
94 views



Related Hot Questions

1 Answer

0 votes
Ofcource this possible.

You need to read the file line by line. Check each line if it contains date1. If it does then extract and parse the data you want.

Here is a sample code how you can achieve this with standard api:

public class ReadFileLineByLineAnExtractSomeText {

    private static final String src = "test.txt";
    private static final String date1 = "March 15, 2013";

    @BeforeClass
    public static void genTextFile() throws IOException {
        OutputStream os = new FileOutputStream(src);
        os.write(("blah bla foo bar\n" +
                "2013001  Jaymarion Manalo L. Service Crew March 15, 2013   8:00   12:00   13:00   17:00   10.0\r\n" +
                "2013001  Jaymarion Manalo L. Service Crew March 16, 2013   8:00   12:05   13:05   17:30   10.0\r" +
                "... the end").getBytes());
        os.close();
    }

    @Test
    public void testReadAndExtract() throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(src));
        String line = br.readLine();
        int lineNumber = 0;
        while(line != null) {
            lineNumber++;
            int i = line.indexOf(date1);
            if(i != -1) {
                int s = i + date1.length();
                int e = line.length();
                System.out.println(date1 + " found in line " + lineNumber  + " at index " + i + ", extract text from " + s + " to " + e);
                String extractedText = line.substring(s, e);
                String[] extractedTextParts = extractedText.trim().split("\\s+");
                for(String part : extractedTextParts) {
                    if(isTime(part)) {
                        System.out.println("    '" + part + "'");   
                    }
                }
            }
            line = br.readLine();
        }
        br.close();
    }

    private boolean isTime(String part) {
        return part == null ? false : part.matches("\\d{1,2}:\\d{1,2}");
    }
}
Output

March 15, 2013 found in line 2 at index 42, extract text from 56 to 94
    '8:00'
    '12:00'
    '13:00'
    '17:00'
answered Jun 18, 2015 by rajesh

...