Java Text File Read by Charset readURL(URL url, Charset encoding)

Here you can find the source of readURL(URL url, Charset encoding)

Description

Read from a url and returns a String of the contents.

License

Open Source License

Parameter

Parameter Description
url a parameter

Exception

Parameter Description
IOException an exception

Declaration

public static String readURL(URL url, Charset encoding) throws IOException 

Method Source Code

//package com.java2s;
/*   //w ww.java 2s.  com
*    Copyright (C) 2013  facetoe - facetoe@ymail.com
*
*    This program 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 2 of the License, or
*    (at your option) any later version.
*
*    This program 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 this program; if not, write to the Free Software Foundation, Inc.,
*    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

import javax.net.ssl.HttpsURLConnection;

import java.io.*;

import java.net.URL;

import java.nio.charset.Charset;

public class Main {
    /**
     * Read from a url and returns a String of the contents.
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static String readURL(URL url, Charset encoding) throws IOException {
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        String line;
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding));
            while ((line = in.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
        } finally {
            connection.getInputStream().close();
        }
        return sb.toString();
    }
}

Related

  1. readTextFile(final String fileNamePath, final String charsetName)
  2. readTextStream(InputStream is, Charset charset)
  3. readToBuffer(StringBuffer buffer, String filePath, Charset charset)
  4. readToString(InputStream in, Charset charset)
  5. readToString(ReadableByteChannel in, Charset charset)
  6. readWholeFile(String filename, String charSet)