hongsgo avatar

Execute Around Pattern

hongsgo

Published: 04 May 2018 › Updated: 04 May 2018Execute Around Pattern

Execute Around Pattern

public class ExecuteAround {
    //data.txt 
    //1 
    //2
    public static final String RESOURCE_FILE_PATH = "data/data.txt";

    @Test
    public void testSingleLine() throws IOException, URISyntaxException {

        File file = new File(getClass().getClassLoader().getResource(RESOURCE_FILE_PATH).toURI());
        assertTrue("1".equals(process(file)));
    }

    public static String process(File file) throws IOException {

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            return br.readLine();
        }
    }

    @Test
    public void testFunctionalInterface() throws IOException, URISyntaxException {

        File file = new File(getClass().getClassLoader().getResource(RESOURCE_FILE_PATH).toURI());
        String result1 = processByFunctionalInterface(file,
                (BufferedReader b) -> b.readLine());
        assertThat(result1, is("1"));

        String result2 = processByFunctionalInterface(file,
                (BufferedReader b) -> b.readLine()
                        + " NextLine " + b
                        .readLine());
        assertThat(result2, is("1 NextLine 2"));
    }

    public static String processByFunctionalInterface(File file, BufferedReaderProcessor p) throws IOException {
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            return p.process(br);
        }
    }

    @FunctionalInterface
    public interface BufferedReaderProcessor {
        String process(BufferedReader b) throws IOException;
    }
}

Leave Execute Around Pattern to:

Written by

Read more #execute posts


Best Posts From hongsgo

We have not curated any of hongsgo's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From hongsgo