Java FileInputStream Read readFile(String path, String encoding)

Here you can find the source of readFile(String path, String encoding)

Description

read File

License

Open Source License

Declaration

public static String readFile(String path, String encoding) throws IOException 

Method Source Code


//package com.java2s;
/*/* ww  w .j av a  2s . c  om*/
 * Copyright (C) 2010 Stephen Tigner
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 */

import java.io.*;

import java.util.Enumeration;
import java.util.zip.*;

public class Main {
    private static final boolean DEBUG = false;
    private static ZipFile zip;
    private static ClassLoader loader;
    private static File parent;

    public static String readFile(String path) throws IOException {
        return readFile(path, "UTF-8");
    }

    public static String readFile(String path, String encoding) throws IOException {
        /* File fileToRead = openFile(path);
         * FileInputStream fis = new FileInputStream(fileToRead);
         * byte[] byteArray = new byte[(int) fileToRead.length()];
         * fis.read(byteArray);
         * fis.close(); */

        byte[] byteArray = loadByteArray(path);

        /* If we don't do it this way, by explicitly setting UTF-8 encoding
         * when reading in a file, we get mojibake (scrambled character encodings).
         */
        String fileContents = new String(byteArray, encoding);
        return fileContents;
    }

    public static byte[] loadByteArray(String filename) throws FileNotFoundException, IOException {
        byte byteArray[];
        if (zip != null || (loader != null && parent == null)) {
            InputStream is = openInFileStream(filename);
            byte buffer[] = new byte[1024];
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int b;
            while ((b = is.read(buffer, 0, 1024)) != -1)
                bos.write(buffer, 0, b);
            bos.flush();
            bos.close();
            is.close();
            byteArray = bos.toByteArray();
        } else {
            File fileToRead = openFile(filename);
            FileInputStream fis = new FileInputStream(fileToRead);
            byteArray = new byte[(int) fileToRead.length()];
            fis.read(byteArray);
            fis.close();
        }
        return byteArray;
    }

    /**
     * Takes a filename string and a command-line label and attempts to open an input
     * stream to the file given in the filename.
     *
     * @param filename - A string with the filename to open
     * @return An InputStream for reading from the file specified.
     * @throws FileNotFoundException
     */
    public static InputStream openInFileStream(String filename) throws FileNotFoundException {

        BufferedInputStream bis = null;
        if (zip != null) {
            try {
                if (filename.startsWith("/"))
                    filename = filename.substring(1);
                ZipEntry entry = zip.getEntry(filename);
                //I we don't find the file at the given path, we will look for it somewhere else
                if (entry == null) {
                    filename = filename.substring(filename.lastIndexOf('/') + 1);
                    Enumeration entries = zip.entries();
                    while (entries.hasMoreElements()) {
                        ZipEntry entryAux = (ZipEntry) entries.nextElement();
                        if (entryAux.getName().endsWith("/" + filename) || entryAux.getName().equals(filename)) {
                            entry = entryAux;
                            break;
                        }
                    }
                }
                if (entry == null)
                    throw new FileNotFoundException("File: " + filename);
                bis = new BufferedInputStream(zip.getInputStream(entry));
                if (DEBUG)
                    System.err.println("openInFileStream in ZIP " + filename);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } else if (loader != null && parent == null) {
            if (filename.startsWith("/"))
                filename = filename.substring(1);
            InputStream is = loader.getResourceAsStream(filename);
            if (is == null)
                throw new FileNotFoundException("File: " + filename);
            bis = new BufferedInputStream(is);
            if (DEBUG)
                System.err.println("openInFileStream in ClassLoader " + filename);
        } else {
            File file = null;
            try {
                file = openFile(filename);
                bis = new BufferedInputStream(new FileInputStream(file));
                if (DEBUG)
                    System.err.println("openInFileStream File " + filename);
            } catch (FileNotFoundException e) {
                throw new FileNotFoundException(
                        "File: " + file.getPath() + " ( " + filename + ") -- " + e.getLocalizedMessage());
            }
        }
        return bis;
    }

    /** Flush if possible */
    public static void flush(Appendable output) throws IOException {
        if (output instanceof Flushable)
            ((Flushable) output).flush();
    }

    /** Close if possible */
    public static void close(Appendable output) throws IOException {
        if (output instanceof Closeable)
            ((Closeable) output).close();
    }

    public static File openFile(String filename) {
        filename = filename.trim();
        File file = new File(filename);
        if (!file.exists()) {
            File aux = new File(parent, filename);
            if (aux.exists())
                file = aux;
        }
        try {
            if (!file.exists() && System.getProperty("os.name").startsWith("Windows")) {
                if (DEBUG) {
                    System.err.println("*** DEBUG: Trying cygwin path...");
                }
                filename = getWindowsPathFromCygwin(filename);
                if (DEBUG) {
                    System.err.println("*** DEBUG: Cygwin path -- " + filename);
                }
                if (filename != null) {
                    File winFile = new File(filename);
                    if (DEBUG) {
                        System.err.println("*** DEBUG: winFile.exists() -- " + winFile.exists());
                        System.err.println("*** DEBUG: winFile.getAbsolutePath() -- " + winFile.getAbsolutePath());
                    }
                    if (winFile.exists()) {
                        file = winFile;
                    }
                    /* If trying to run it through cygwin fails, just return the
                     * original file object, created with the original path.
                     */
                }
            }
        } catch (Exception e) {
        }
        return file;
    }

    /**
     * Given a cygwin unix-style path, this calls the external cygwin utility
     * "cygpath" to return the equivalent Windows path.
     * This assumes that "cygpath" is on the user's path. It should be if they have
     * cygwin installed, but if it is not on the user's path, then we can't run it.
     *
     * @param filename -- The cygwin unix-style path and filename to convert
     * @return A windows-style path for that same filename that was input.
     */
    public static String getWindowsPathFromCygwin(String filename) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try {
            Process extProcess = Runtime.getRuntime().exec("cygpath -m " + filename);
            extProcess.waitFor();
            if (extProcess.exitValue() != 0) {
                /* Assume process follows convention of 0 == Success.
                 * Thus if the exit value is != 0, it failed
                 */
                return null;
            }
            int currByte;
            while ((currByte = extProcess.getInputStream().read()) != -1) {
                output.write(currByte);
            }
            return output.toString("UTF-8");
        } catch (Exception e) { //catch all exceptions and discard them, returning null
            e.printStackTrace();
            return null;
        }
    }
}

Related

  1. readFile(String path)
  2. readFile(String path)
  3. readFile(String path)
  4. readFile(String path, long offset)
  5. readFile(String path, Properties store)
  6. readFile(String path, String root, OutputStream out)
  7. readFile(String pPathToFile)
  8. readFile(String resource)
  9. readFile(String sFileName)