Execute Around Pattern

in #execute7 years ago
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;
    }
}

Coin Marketplace

STEEM 0.17
TRX 0.24
JST 0.034
BTC 96135.63
ETH 2796.94
SBD 0.66