Java Resource File loadUTF8(String resource)

Here you can find the source of loadUTF8(String resource)

Description

load UTF

License

Apache License

Declaration

public static String loadUTF8(String resource) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.*;
import java.net.URL;

public class Main {
    public static String loadUTF8(String resource) throws IOException {
        File source = getFile(resource);
        if (source == null) {
            return null;
        }/*from   ww w . j  av a2 s . c  om*/
        InputStream in = new FileInputStream(source);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        pipe(in, bos);
        in.close();
        return bos.toString("utf-8");
    }

    /**
     * Multi protocol resource loader. Primary attempt is direct file, secondary is classpath resolved to File.
     *
     * @param resource a generic resource.
     * @return a File pointing to the resource.
     */
    public static File getFile(String resource) throws IOException {
        File directFile = new File(resource);
        if (directFile.exists()) {
            return directFile;
        }
        URL classLoader = Thread.currentThread().getContextClassLoader().getResource(resource);
        if (classLoader == null) {
            throw new FileNotFoundException("Unable to locate '" + resource + "' as direct File or on classpath");
        }
        String fromURL = classLoader.getFile();
        if (fromURL == null || fromURL.isEmpty()) {
            throw new FileNotFoundException("Unable to convert URL '" + fromURL + "' to File");
        }
        return new File(fromURL);
    }

    private static void pipe(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        out.flush();
    }
}

Related

  1. getTestResourceFile(String pName, Class pClass)
  2. inputStream(Class baseClass, String resourceName)
  3. isFullIRI(String resource)
  4. loadAutoConfigFiles(ClassLoader classLoader, String resourceName)
  5. loadConfigFile(String resource, Class clazz)
  6. openInputStream(String resourceString, ClassLoader classLoader)
  7. parseASX(String inputResource)
  8. printUsage(ResourceBundle bundle)
  9. put(String resource, Map headers, String data)