Java URL Download nio downloadToString(String url)

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

Description

download To String

License

Open Source License

Declaration

public static String downloadToString(String url) 

Method Source Code


//package com.java2s;
/*/*w  w  w.  ja va 2  s  . c  om*/
 * Xapp (pronounced Zap!), A automatic gui tool for Java.
 * Copyright (C) 2009 David Webber. All Rights Reserved.
 *
 * The contents of this file may be used under the terms of the GNU Lesser
 * General Public License Version 2.1 or later.
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 */

import java.io.*;
import java.nio.charset.Charset;

import java.net.URL;
import java.net.MalformedURLException;

public class Main {
    public static String downloadToString(String url) {
        InputStream inputStream = openStream(url);
        if (inputStream == null) {
            return null;
        }
        return new String(streamToByteArray(inputStream), Charset.forName("UTF-8"));
    }

    public static InputStream openStream(String urlStr) {
        URL url;
        try {
            url = new URL(urlStr);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
        InputStream in;
        try {
            in = url.openStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return in;
    }

    private static byte[] streamToByteArray(InputStream in) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int i;
            while ((i = in.read()) != -1) {
                baos.write(i);
            }
            byte[] byteArray = baos.toByteArray();
            return byteArray;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. downloadFromHttpUrl(String destPkgUrl, FileOutputStream outputStream)
  2. downloadFromInternet(URL url, File downloadTo)
  3. downloadImage(String src, Path saveFolder)
  4. downloadToFile(String filename, String urlString)
  5. downloadToFile(URL url, File file)
  6. downloadUrl(String urlstring, File file)