Java URL Load readURLToString(URL u, String encoding)

Here you can find the source of readURLToString(URL u, String encoding)

Description

Reads a string from a URL

License

Apache License

Parameter

Parameter Description
u the URL
encoding the character encoding

Exception

Parameter Description
IOException if the URL contents could not be read

Return

the string

Declaration

public static String readURLToString(URL u, String encoding)
        throws IOException 

Method Source Code

//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class Main {
    /**/*from ww w.j av  a  2  s .  c  o  m*/
     * Reads a string from a URL
     * @param u the URL
     * @param encoding the character encoding
     * @return the string
     * @throws IOException if the URL contents could not be read
     */
    public static String readURLToString(URL u, String encoding)
            throws IOException {
        return readStreamToString(u.openStream(), encoding);
    }

    /**
     * Reads a string from a stream. Closes the stream after reading.
     * @param is the stream
     * @param encoding the character encoding
     * @return the string
     * @throws IOException if the stream contents could not be read
     */
    public static String readStreamToString(InputStream is, String encoding)
            throws IOException {
        try {
            StringBuilder sb = new StringBuilder();
            byte[] buf = new byte[1024 * 10];
            int read;
            while ((read = is.read(buf)) >= 0) {
                sb.append(new String(buf, 0, read, encoding));
            }
            return sb.toString();
        } finally {
            is.close();
        }
    }
}

Related

  1. readURLText(String urlPath, String encoding)
  2. readUrlText(String urlString)
  3. readURLText(URL url, StringBuffer errorText)
  4. readURLThrowException(final String url)
  5. readURLToByteArray(URL url)
  6. saveFile(final URL url, final File file)
  7. saveFileFromURL(URL url, File destinationFile)
  8. saveImage(String imageUrl, String destinationFile)
  9. saveImageAsFile(String imageUrl, String destinationFile, boolean overwrite)