Java URL Load readURL(String url)

Here you can find the source of readURL(String url)

Description

read URL

License

Open Source License

Return

the contents of the resource as a string, or null if the contents of the resource could not be located using url

Declaration

public static String readURL(String url) throws java.io.IOException 

Method Source Code


//package com.java2s;
/*// w  ww. ja va2 s. co  m
 *        JacORB  - a free Java ORB
 *
 *   Copyright (C) 1997-2014 Gerald Brose / The JacORB Team.
 *
 *   This library is free software; you can redistribute it and/or
 *   modify it under the terms of the GNU Library General Public
 *   License as published by the Free Software Foundation; either
 *   version 2 of the License, or (at your option) any later version.
 *
 *   This library is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *   Library General Public License for more details.
 *
 *   You should have received a copy of the GNU Library General Public
 *   License along with this library; if not, write to the Free
 *   Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.net.MalformedURLException;

public class Main {
    /**
     * @return the contents of the resource as a string, or null
     * if the contents of the resource could not be located using url
     */
    public static String readURL(String url) throws java.io.IOException {
        final BufferedReader reader = new BufferedReader(newInputStreamReader(url));

        try {
            return reader.readLine();
        } finally {
            reader.close();
        }
    }

    private static java.io.InputStreamReader newInputStreamReader(String url)
            throws MalformedURLException, IOException {
        String token = "file://";
        java.io.InputStreamReader isr = null;
        if (url.startsWith(token)) {
            try {
                isr = new java.io.FileReader(url.substring(token.length()));
            } catch (Exception e) {
                System.out.println("Tried and failed to open file: " + url.substring(token.length()));
                // no worries, let the URL handle it
            }
        }

        if (isr == null) {
            java.net.URL urlCopy = new java.net.URL(url);
            isr = new java.io.InputStreamReader(urlCopy.openStream());
        }
        return isr;
    }
}

Related

  1. readURL(final URL url)
  2. readUrl(final URL url)
  3. readUrl(final URL url)
  4. readURL(String URL)
  5. readURL(String url)
  6. readURL(String url, String charsetName)
  7. ReadURL(String URLAddress)
  8. readUrl(String urlString)
  9. readURL(URL fileURL)