Example usage for java.io FileInputStream read

List of usage examples for java.io FileInputStream read

Introduction

In this page you can find the example usage for java.io FileInputStream read.

Prototype

public int read(byte b[]) throws IOException 

Source Link

Document

Reads up to b.length bytes of data from this input stream into an array of bytes.

Usage

From source file:it.geosolutions.tools.compress.file.Compressor.java

/**
 * This function zip the input directory.
 * /*from w  w  w  .ja  v  a2s .c o m*/
 * @param directory
 *            The directory to be zipped.
 * @param base
 *            The base directory.
 * @param out
 *            The zip output stream.
 * @throws IOException
 */
public static void zipDirectory(final File directory, final File base, final ZipOutputStream out)
        throws IOException {

    if (directory != null && base != null && out != null) {
        File[] files = directory.listFiles();
        byte[] buffer = new byte[4096];
        int read = 0;

        FileInputStream in = null;
        ZipEntry entry = null;

        try {
            for (int i = 0, n = files.length; i < n; i++) {
                if (files[i].isDirectory()) {
                    zipDirectory(files[i], base, out);
                } else {
                    in = new FileInputStream(files[i]);
                    entry = new ZipEntry(base.getName().concat("\\")
                            .concat(files[i].getPath().substring(base.getPath().length() + 1)));
                    out.putNextEntry(entry);

                    while (-1 != (read = in.read(buffer))) {
                        out.write(buffer, 0, read);
                    }

                    // //////////////////////
                    // Complete the entry
                    // //////////////////////

                    out.closeEntry();

                    in.close();
                    in = null;
                }
            }

        } catch (IOException e) {
            if (LOGGER.isErrorEnabled())
                LOGGER.error(e.getLocalizedMessage(), e);
            if (out != null)
                out.close();
        } finally {
            if (in != null)
                in.close();
        }

    } else
        throw new IOException("One or more input parameters are null!");
}

From source file:at.tugraz.sss.serv.SSFileU.java

public static void readFileBytes(final OutputStream outStream, final FileInputStream fileIn) throws Exception {

    if (SSObjU.isNull(outStream, fileIn)) {
        throw new Exception("pars not okay");
    }/*from   w w w.  ja v a2 s  .com*/

    final byte[] fileBytes = new byte[SSSocketU.socketTranmissionSize];
    int read;

    try {

        while ((read = fileIn.read(fileBytes)) != -1) {

            if (fileBytes.length == 0 || read <= 0) {

                outStream.write(new byte[0]);
                outStream.flush();
                break;
            }

            outStream.write(fileBytes, 0, read);
            outStream.flush();
        }
    } catch (Exception error) {
        throw error;
    } finally {

        if (outStream != null) {
            outStream.close();
        }

        if (fileIn != null) {
            fileIn.close();
        }
    }
}

From source file:com.fjn.helper.common.io.file.common.FileUpAndDownloadUtil.java

public static void downloadToBrowser(String filename, String realpath, HttpServletRequest request,
        HttpServletResponse response) {/*from   w  w  w.jav  a2 s  .  co  m*/
    // ?MIME TYPE?
    //try {
    //      mimetypesMap=new MimetypesFileTypeMap(request.getSession().getServletContext().getRealPath("WEB-INF/my.mime.types"));
    mimetypesMap = new MimetypesFileTypeMap();
    //} catch (IOException e1) {
    //   e1.printStackTrace();
    //}

    //   response.setCharacterEncoding("UTF-8");
    response.setContentType(mimetypesMap.getContentType(filename));
    response.addHeader("Content-Disposition", "attachment;filename=" + toUTF8(filename));
    FileInputStream in = null;
    OutputStream out = null;
    try {
        /*   ????
           BufferedReader in = new BufferedReader(new InputStreamReader(
                 new FileInputStream(new File(realpath))));
           BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
                 response.getOutputStream()));
           int length = -1;
           char[] chs = new char[1024];
           while ((length = in.read(chs)) != -1) {
              out.write(chs, 0, length);
           }
        */
        in = new FileInputStream(new File(realpath));
        out = response.getOutputStream();
        int length = -1;
        byte[] bs = new byte[1024];
        while ((length = in.read(bs)) != -1) {
            out.write(bs, 0, length);
        }

        out.flush();

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null)
                out.close();
            if (in != null)
                in.close();
        } catch (Exception ex) {

        }
    }

}

From source file:marytts.util.io.FileUtils.java

public static void copy(String sourceFile, String destinationFile) throws IOException {
    File fromFile = new File(sourceFile);
    File toFile = new File(destinationFile);

    if (!fromFile.exists()) {
        throw new IOException("FileCopy: " + "no such source file: " + sourceFile);
    }/*from  www  . j  ava  2  s .c o m*/
    if (!fromFile.isFile()) {
        throw new IOException("FileCopy: " + "can't copy directory: " + sourceFile);
    }
    if (!fromFile.canRead()) {
        throw new IOException("FileCopy: " + "source file is unreadable: " + sourceFile);
    }

    if (toFile.isDirectory()) {
        toFile = new File(toFile, fromFile.getName());
    }

    if (toFile.exists()) {
        if (!toFile.canWrite()) {
            throw new IOException("FileCopy: " + "destination file cannot be written: " + destinationFile);
        }
    }

    String parent = toFile.getParent();
    if (parent == null) {
        parent = System.getProperty("user.dir");
    }
    File dir = new File(parent);
    if (!dir.exists()) {
        throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent);
    }
    if (dir.isFile()) {
        throw new IOException("FileCopy: " + "destination is not a directory: " + parent);
    }
    if (!dir.canWrite()) {
        throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent);
    }

    FileInputStream from = null;
    FileOutputStream to = null;
    try {
        from = new FileInputStream(fromFile);
        to = new FileOutputStream(toFile);
        byte[] buffer = new byte[4096];
        int bytesRead;

        while ((bytesRead = from.read(buffer)) != -1) {
            to.write(buffer, 0, bytesRead); // write
        }
    } finally {
        close(from, to);
    }
}

From source file:isl.FIMS.utils.Utils.java

public static void createZip(String zipFile, String sourceDirectory) {
    try {/*w w  w  .ja  v a  2s.  com*/
        // String zipFile = "C:/FileIO/zipdemo.zip";
        // String sourceDirectory = "C:/examples";

        //create byte buffer
        byte[] buffer = new byte[1024];
        //create object of FileOutputStream
        FileOutputStream fout = new FileOutputStream(zipFile);
        //create object of ZipOutputStream from FileOutputStream
        ZipOutputStream zout = new ZipOutputStream(fout);
        //create File object from directory name
        File dir = new File(sourceDirectory);

        //check to see if this directory exists
        if (!dir.isDirectory()) {
        } else {
            File[] files = dir.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile()) {
                    //create object of FileInputStream for source file
                    FileInputStream fin = new FileInputStream(files[i]);
                    zout.putNextEntry(new ZipEntry(files[i].getName()));
                    int length;
                    while ((length = fin.read(buffer)) > 0) {
                        zout.write(buffer, 0, length);
                    }
                    zout.closeEntry();
                    //close the InputStream
                    fin.close();
                }
            }
        }

        //close the ZipOutputStream
        zout.close();
    } catch (IOException ioe) {
    }
}

From source file:at.tugraz.sss.serv.util.SSFileU.java

public static String readFileText(final File file, final Charset charset) throws SSErr {

    FileInputStream in = null;

    try {//w w  w .ja v  a2s .  c o  m

        final byte[] bytes = new byte[1];
        String fileContent = SSStrU.empty;

        in = openFileForRead(file.getAbsolutePath());

        while (in.read(bytes) != -1) {
            fileContent += new String(bytes, charset);
        }

        in.close();

        return fileContent;
    } catch (Exception error) {
        SSServErrReg.regErrThrow(error);
        return null;
    } finally {

        if (in != null) {
            try {
                in.close();
            } catch (IOException ex) {
                SSLogU.err(ex);
            }
        }
    }
}

From source file:gmgen.util.MiscUtilities.java

/**
 * Copy a file//from   w  ww . j a v a2 s  . c  o m
 * @param from_file
 * @param to_file
 * @throws IOException
 */
public static void copy(File from_file, File to_file) throws IOException {
    // First make sure the source file exists, is a file, and is readable.
    if (!from_file.exists()) {
        throw new IOException("FileCopy: no such source file: " + from_file.getPath());
    }

    if (!from_file.isFile()) {
        throw new IOException("FileCopy: can't copy directory: " + from_file.getPath());
    }

    if (!from_file.canRead()) {
        throw new IOException("FileCopy: source file is unreadable: " + from_file.getPath());
    }

    // If the destination is a directory, use the source file name
    // as the destination file name
    if (to_file.isDirectory()) {
        to_file = new File(to_file, from_file.getName());
    }

    // If the destination exists, make sure it is a writeable file
    // and ask before overwriting it.  If the destination doesn't
    // exist, make sure the directory exists and is writeable.
    if (to_file.exists()) {
        if (!to_file.canWrite()) {
            throw new IOException("FileCopy: destination file is unwriteable: " + to_file.getPath());
        }

        // Ask whether to overwrite it
        int choice = JOptionPane.showConfirmDialog(null, "Overwrite existing file " + to_file.getPath(),
                "File Exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

        if (choice != JOptionPane.YES_OPTION) {
            throw new IOException("FileCopy: existing file was not overwritten.");
        }
    } else {
        // if file doesn't exist, check if directory exists and is writeable.
        // If getParent() returns null, then the directory is the current dir.
        // so look up the user.dir system property to find out what that is.
        String parent = to_file.getParent(); // Get the destination directory

        if (parent == null) {
            parent = Globals.getDefaultPath(); // or CWD
        }

        File dir = new File(parent); // Convert it to a file.

        if (!dir.exists()) {
            throw new IOException("FileCopy: destination directory doesn't exist: " + parent);
        }

        if (dir.isFile()) {
            throw new IOException("FileCopy: destination is not a directory: " + parent);
        }

        if (!dir.canWrite()) {
            throw new IOException("FileCopy: destination directory is unwriteable: " + parent);
        }
    }

    // If we've gotten this far, then everything is okay.
    // So we copy the file, a buffer of bytes at a time.
    FileInputStream from = null; // Stream to read from source
    FileOutputStream to = null; // Stream to write to destination

    try {
        from = new FileInputStream(from_file); // Create input stream
        to = new FileOutputStream(to_file); // Create output stream

        byte[] buffer = new byte[4096]; // A buffer to hold file contents
        int bytes_read; // How many bytes in buffer

        while ((bytes_read = from.read(buffer)) != -1) { // Read bytes until EOF
            to.write(buffer, 0, bytes_read); //   write bytes
        }
    }

    // Always close the streams, even if exceptions were thrown
    finally {
        if (from != null) {
            try {
                from.close();
            } catch (IOException e) {
                //TODO: Should this really be ignored?
            }
        }

        if (to != null) {
            try {
                to.close();
            } catch (IOException e) {
                //TODO: Should this really be ignored?
            }
        }
    }
}

From source file:gov.nasa.ensemble.common.io.FileUtilities.java

/**
 * This function will copy files or directories from one location to another. note that the source and the destination must be mutually exclusive. This function can not be used to copy a directory
 * to a sub directory of itself. The function will also have problems if the destination files already exist.
 * //  w w w  . j  av  a  2 s.  com
 * @param src
 *            -- A File object that represents the source for the copy
 * @param dest
 *            -- A File object that represnts the destination for the copy.
 * @throws IOException
 *             if unable to copy.
 */
public static void copyFiles(File src, File dest) throws IOException {
    // Check to ensure that the source is valid...
    if (!src.exists()) {
        throw new IOException("copyFiles: Can not find source: " + src.getAbsolutePath() + ".");
    } else if (!src.canRead()) { // check to ensure we have rights to the source...
        throw new IOException("copyFiles: No right to source: " + src.getAbsolutePath() + ".");
    }
    // is this a directory copy?
    if (src.isDirectory()) {
        if (!dest.exists()) { // does the destination already exist?
            // if not we need to make it exist if possible (note this is mkdirs not mkdir)
            if (!dest.mkdirs()) {
                throw new IOException("copyFiles: Could not create direcotry: " + dest.getAbsolutePath() + ".");
            }
        }
        // get a listing of files...
        String list[] = src.list();
        // copy all the files in the list.
        for (int i = 0; i < list.length; i++) {
            File dest1 = new File(dest, list[i]);
            File src1 = new File(src, list[i]);
            copyFiles(src1, dest1);
        }
    } else {
        // This was not a directory, so lets just copy the file
        FileInputStream fin = null;
        FileOutputStream fout = null;
        byte[] buffer = new byte[4096]; // Buffer 4K at a time (you can change this).
        int bytesRead;
        try {
            // open the files for input and output
            fin = new FileInputStream(src);
            fout = new FileOutputStream(dest);
            // while bytesRead indicates a successful read, lets write...
            while ((bytesRead = fin.read(buffer)) >= 0) {
                fout.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) { // Error copying file...
            IOException wrapper = new IOException("copyFiles: Unable to copy file: " + src.getAbsolutePath()
                    + "to" + dest.getAbsolutePath() + ".");
            wrapper.initCause(e);
            wrapper.setStackTrace(e.getStackTrace());
            throw wrapper;
        } finally { // Ensure that the files are closed (if they were open).
            if (fin != null) {
                fin.close();
            }
            if (fout != null) {
                fout.close();
            }
        }
    }
}

From source file:com.baidu.rigel.biplatform.tesseract.util.FileUtils.java

/**
 * ?/*from w ww .j av a  2  s . c om*/
 * 
 * @param oldPath
 *            String  c:/fqf
 * @param newPath
 *            String ?? f:/fqf/ff
 * @return boolean
 * @throws Exception
 */
public static void copyFolder(String oldPath, String newPath) throws Exception {
    LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_BEGIN, "copyFolder",
            "[oldPath:" + oldPath + "][newPath:+" + newPath + "]"));
    try {

        File newPathFile = new File(newPath);
        newPathFile.mkdirs();

        File oldPathFile = new File(oldPath);
        String[] file = oldPathFile.list();
        File temp = null;
        for (int i = 0; i < file.length; i++) {
            if (oldPath.endsWith(File.separator)) {
                temp = new File(oldPath + file[i]);
            } else {
                temp = new File(oldPath + File.separator + file[i]);
            }

            if (temp.isFile()) {
                FileInputStream input = new FileInputStream(temp);
                FileOutputStream output = new FileOutputStream(
                        newPath + File.separator + (temp.getName()).toString());
                byte[] b = new byte[1024 * 5];
                int len;
                while ((len = input.read(b)) != -1) {
                    output.write(b, 0, len);
                }
                output.flush();
                output.close();
                input.close();
            }
            if (temp.isDirectory()) {
                // ?
                copyFolder(oldPath + File.separator + file[i], newPath + File.separator + file[i]);
            }
        }
    } catch (Exception e) {
        LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_EXCEPTION, "copyFolder",
                "[oldPath:" + oldPath + "][newPath:+" + newPath + "]"));
        throw e;

    }

    LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_END, "copyFolder",
            "[oldPath:" + oldPath + "][newPath:+" + newPath + "]"));

}

From source file:isl.FIMS.utils.Utils.java

private static void copyFile(java.io.File destination, java.io.File source) throws Exception {
    try {//from   w w w . j  ava2s  . co  m
        java.io.FileInputStream inStream = new java.io.FileInputStream(source);
        java.io.FileOutputStream outStream = new java.io.FileOutputStream(destination);

        int len;
        byte[] buf = new byte[2048];

        while ((len = inStream.read(buf)) != -1) {
            outStream.write(buf, 0, len);
        }
    } catch (Exception e) {
        throw new Exception("Can't copy file " + source + " -> " + destination + ".", e);
    }
}