Java URL Load readStringFromURL(URL url)

Here you can find the source of readStringFromURL(URL url)

Description

read String From URL

License

Open Source License

Declaration

public static String readStringFromURL(URL url) 

Method Source Code

//package com.java2s;
/*/*from www. j  av a 2 s  .c  o  m*/
 * SwingTech Software - http://cooksarm.sourceforge.net/
 *
 * Copyright (C) 2011 Joe Rice
 * All rights reserved.
 * 
 * SwingTech Cooks Arm is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation; either version 3 of the License,
 * or (at your option) any later version.
 *
 * SwingTech Cooks Arm 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
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with SwingTech Cooks Arm; If not, see <http://www.gnu.org/licenses/>. 
 * 
 */

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;

public class Main {
    public static String readStringFromURL(URL url) {
        InputStream is = null;

        try {
            is = url.openStream();
        } catch (IOException e) {
            return "";
        }

        return readStringFromInputStream(is);
    }

    public static String readStringFromInputStream(InputStream input) {
        Writer writer = null;

        try {
            if (input != null) {
                try {
                    writer = new StringWriter();

                    char[] buffer = new char[1024];
                    Reader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
                    int n;
                    while ((n = reader.read(buffer)) != -1) {
                        writer.write(buffer, 0, n);
                    }
                } finally {
                    input.close();
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        return writer.toString();
    }
}

Related

  1. readResource(URL resource)
  2. readServicesFromUrl(Collection list, URL url)
  3. readSqlStatements(URL url)
  4. readStopwordsURL(URL url, boolean lowercase)
  5. readStringFromUrl(URL url)
  6. readText(final URL url)
  7. readText(final URL url)
  8. readTextFile(final URL resource)
  9. readTextFileAtUrl(final URL url)