Java URL Load load(String fileOrURL)

Here you can find the source of load(String fileOrURL)

Description

Load entire contents of a file or URL into a string.

License

Open Source License

Declaration

public static String load(String fileOrURL) throws IOException 

Method Source Code


//package com.java2s;
import java.net.*;
import java.io.*;

public class Main {
    /**//from   w  ww . j  a v a  2s  . c o m
     * Load entire contents of a file or URL into a string.
     */
    public static String load(String fileOrURL) throws IOException {
        try {
            URL url = new URL(fileOrURL);

            return new String(loadURL(url));
        } catch (Exception e) {
            return loadFile(fileOrURL);
        }
    }

    public static byte[] loadURL(URL url) throws IOException {
        int bufSize = 1024 * 2;
        byte[] buf = new byte[bufSize];

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        BufferedInputStream in = new BufferedInputStream(url.openStream());
        int n;
        while ((n = in.read(buf)) > 0) {
            bout.write(buf, 0, n);
        }
        try {
            in.close();
        } catch (Exception ignored) {
        }
        return bout.toByteArray();
    }

    public static String loadFile(String fname) throws IOException {
        byte[] bytes = loadURL(new URL("file:" + fname));
        return new String(bytes, "UTF-8");
    }
}

Related

  1. findResourcesFromJar(Collection urls, URL url, String resource, ClassLoader cl)
  2. getBundle(String basename, Locale locale, ClassLoader cl, URL url)
  3. getManifestAsString(URLClassLoader cl, String jarBaseName)
  4. load(Iterable urls)
  5. load(URL pUrl)
  6. load(URL url)
  7. load(URL url)
  8. load(URL url, boolean allowCache)