Code, JavaEE, SOA, Technical, WebServices

Read Remote File Contents

@Test
public void formatOutput() {
    final String routerJS =
            "static/master/router.js";
    readRemoteFileContents(routerJS);
}

private void readRemoteFileContents(final String fileToRead) {
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection)githubURL(fileToRead).openConnection();
    } catch (IOException e) {
        e.printStackTrace();
    }

    Scanner scanner = null;
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
        scanner = new Scanner(
                new StringReader(
                        reader.lines().collect(
                                Collectors.joining(System.getProperty("line.separator")))))
        .useDelimiter(System.getProperty("line.separator"));

        while(scanner.hasNext()) {
            System.out.printf("%s%n", scanner.next());
        }
    } catch (IOException e) {

    } finally {
        if (scanner != null) scanner.close();
        if (connection != null) connection.disconnect();
    }

}

private URL githubURL(final String fileToRead) throws MalformedURLException {
    final String baseGitHubFiles = "https://raw.githubusercontent.com/enterprisesaas/";
    final StringBuilder url = new StringBuilder(baseGitHubFiles).append(fileToRead);
    return new URL(url.toString());
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s