Java ClassLoader Load getFileContents(String path)

Here you can find the source of getFileContents(String path)

Description

Uses the toURL() call to convert the path and as a result can find files on the classpath.

License

Open Source License

Parameter

Parameter Description
path the path to the file

Exception

Parameter Description
IOException if the file doe not exist

Return

the contents of the file referenced to by the supplied path

Declaration

public static String getFileContents(String path) throws IOException 

Method Source Code

//package com.java2s;
/*/*  w w  w . j av  a2  s  . co  m*/
 Copyright (C) 2001 - 2010 The Software Conservancy as Trustee. All rights reserved.
    
 Permission is hereby granted, free of charge, to any person obtaining a copy of
 this software and associated documentation files (the "Software"), to deal in the
 Software without restriction, including without limitation the rights to use, copy,
 modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
 and to permit persons to whom the Software is furnished to do so, subject to the
 following conditions:
    
 The above copyright notice and this permission notice shall be included in all 
 copies or substantial portions of the Software.
    
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    
 Nothing in this notice shall be deemed to grant any rights to trademarks, copyrights,
 patents, trade secrets or any other intellectual property of the licensor or any
 contributor except as expressly stated herein. No patent license is granted separate
 from the Software, for code that you delete from the Software, or for combinations
 of the Software with other software or hardware.
*/

import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;

public class Main {
    /**
     * Uses the toURL() call to convert the path and as a result can find files on the classpath.
     * 
     * @param path
     *          the path to the file
     * 
     * @return the contents of the file referenced to by the supplied path
     * 
     * @throws IOException
     *           if the file doe not exist
     */
    public static String getFileContents(String path) throws IOException {
        URL url = toURL(path);
        if (url == null)
            throw new IOException("File not found: " + path);

        return getFileContents(new FileInputStream(url.getPath()));
    }

    /**
     * @param file
     *          reference to the file
     * 
     * @return the contents of the file referenced to by the supplied file and returns its contents as a string
     * 
     * @throws IOException
     *           if the file doe not exist
     */
    public static String getFileContents(File file) throws IOException {
        if (file == null)
            throw new IOException("Null file passed");

        if (!file.exists())
            throw new IOException("File not found: " + file.getPath());

        return getFileContents(new FileInputStream(file));
    }

    /**
     * @param fstream
     *          the stream used to access the file contents
     * 
     * @return the contents of the file referenced by the input stream supplied. The file is processed in 1K chunks.
     * 
     * @throws IOException
     *           if the file doe not exist
     */
    public static String getFileContents(InputStream fstream) throws IOException {
        InputStreamReader in = new InputStreamReader(fstream);

        StringWriter writer = new StringWriter();
        char[] buf = new char[1024];
        int count;

        while ((count = in.read(buf)) != -1)
            writer.write(buf, 0, count);

        in.close();
        fstream.close();

        return writer.toString();
    }

    /**
     * Returns an URL to the supplied file. Will search the classpath if required.
     * 
     * @param path
     *          the path to convert
     * 
     * @return a URL pointing to the file represented by the supplied path string or null if it does not exist
     */
    public static URL toURL(String path) {
        URL url;
        try {
            /*
             * Let java do the work instead of us... if ( path.indexOf(":") == -1 ) url = new URL("file:" + path); else url =
             * new URL(path);
             */
            // todo: the File() constructor will not fail so we will not use the Classloasder
            url = new File(path).toURL();
        } catch (MalformedURLException e) {
            url = ClassLoader.getSystemResource(path);
        }

        return url;
    }
}

Related

  1. getDirectories(String path)
  2. getFile(final String filename)
  3. getFile(final String name)
  4. getFile(Object obj, String filename)
  5. getFileContents(String filename)
  6. getFileFromPath(Object obj, String fileName)
  7. getFileFromPool(String path)
  8. getFileFullPath(String file)
  9. getFilesInPackage(String packageName)