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[], int off, int len) throws IOException 

Source Link

Document

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

Usage

From source file:com.microsoft.tfs.core.util.FileEncodingDetector.java

/**
 * Detects the encoding used for a server or local path with hints. For
 * server paths, the contents are never read and only the hint is used.
 * <p>/*from   w w w  .  jav  a 2s .  com*/
 * The {@link FileEncoding#AUTOMATICALLY_DETECT} encoding hint is only valid
 * for local (not server) paths that do not contain wildcard characters,
 * exist on disk, and are files (not directories). If it is specified for
 * other kinds of paths, an exception is thrown.
 * <p>
 * Encoding hints are evaluated in the following way:
 * <ul>
 * <li>If the hint is {@link FileEncoding#BINARY} that encoding is returned
 * immediately for all item types.</li>
 * <li>If the hint is {@link FileEncoding#DEFAULT_TEXT} the default encoding
 * for this platform is returned immediately for all item types.</li>
 * <li>If the hint is something other than
 * {@link FileEncoding#AUTOMATICALLY_DETECT}, that encoding is returned
 * immediately for all item types.</li>
 * <li>The hint is {@link FileEncoding#AUTOMATICALLY_DETECT}:
 * <ul>
 * <li>If the path is a server path, is a local directory, or contains
 * wildcards, an exception is thrown.</li>
 * <li>The file's contents are read to determine the encoding, which is
 * returned.</li>
 * </ul>
 * </li>
 * </ul>
 *
 * @param path
 *        the path to detect encoding for (must not be <code>null</code>)
 * @param encodingHint
 *        the encoding hint (must not be <code>null</code>)
 * @return the {@link FileEncoding} that matches the given file's encoding.
 * @throws TECoreException
 *         if the specified encoding hint is not valid for the type of path
 *         given
 */
public static FileEncoding detectEncoding(final String path, final FileEncoding encodingHint) {
    tracer.trace(MessageFormat.format("path={0}, encodingHint={1}", path, encodingHint)); //$NON-NLS-1$

    Check.notNull(path, "path"); //$NON-NLS-1$
    Check.notNull(encodingHint, "encodingHint"); //$NON-NLS-1$

    // These hints apply immediately to all types of paths.

    if (encodingHint == FileEncoding.BINARY) {
        return encodingHint;
    } else if (encodingHint == FileEncoding.DEFAULT_TEXT) {
        return FileEncoding.getDefaultTextEncoding();
    } else if (encodingHint != FileEncoding.AUTOMATICALLY_DETECT) {
        return encodingHint;
    }

    // The encoding is FileEncoding.AUTOMATICALLY_DETECT

    if (ServerPath.isServerPath(path)) {
        throw new TECoreException(
                MessageFormat.format(Messages.getString("FileEncodingDetector.ServerPathsNotDetectedFormat"), //$NON-NLS-1$
                        path));
    } else if (Wildcard.isWildcard(path)) {
        throw new TECoreException(MessageFormat.format(
                Messages.getString("FileEncodingDetector.LocalItemContainsWildcardsFormat"), //$NON-NLS-1$
                path));
    }

    // The path is a local path without wildcards

    final File file = new File(LocalPath.canonicalize(path));

    if (file.exists() == false) {
        throw new TECoreException(
                MessageFormat.format(Messages.getString("FileEncodingDetector.LocalItemDoesNotExistFormat"), //$NON-NLS-1$
                        path));
    } else if (file.isDirectory()) {
        throw new TECoreException(
                MessageFormat.format(Messages.getString("FileEncodingDetector.LocalItemIsDirectoryFormat"), //$NON-NLS-1$
                        path));
    }

    FileInputStream stream = null;

    try {
        stream = new FileInputStream(path);

        final byte[] buffer = new byte[1024];

        // Look for the Unicode Byte Order Mark (BOM).
        final int read = stream.read(buffer, 0, buffer.length);

        if (read < 0) {
            return FileEncoding.getDefaultTextEncoding();
        }

        /*
         * Examine the BOM for details. Java uses signed bytes, so we use
         * (signed) integers for easier comparison.
         */
        if (read >= 2 && buffer[0] == -2 && buffer[1] == -1) {
            return FileEncoding.UTF_16BE;
        } else if (read >= 2 && buffer[0] == -1 && buffer[1] == -2) {
            if (read >= 4 && buffer[2] == 0 && buffer[3] == 0) {
                return FileEncoding.UTF_32;
            } else {
                return FileEncoding.UTF_16;
            }
        } else if (read >= 3 && buffer[0] == -17 && buffer[1] == -69 && buffer[2] == -65) {
            return FileEncoding.UTF_8;
        } else if (read >= 4 && buffer[0] == 0 && buffer[1] == 0 && buffer[2] == -2 && buffer[3] == -1) {
            return FileEncoding.UTF_32BE;
        } else if (startsWithPDFHeader(buffer, buffer.length)) {
            /*
             * We go out of our way to detect PDF files so we can claim
             * they're all binary. This is because a PDF file can be created
             * with no non-text bytes in the first 1024 bytes (or in the
             * whole file itself). However, these files shouldn't ever be
             * automatically merged, and in the case where the first 1024
             * bytes are clean, there may lie non-text bytes near the end.
             */
            return FileEncoding.BINARY;
        }

        /*
         * No encoding determined yet. Search the chunk we read for
         * "non-text" characters that would indicate this is not a text
         * file. The values we search for on z/OS are for EBCDIC, the others
         * use ASCII.
         */
        if (Platform.isCurrentPlatform(Platform.Z_OS)) {
            if (looksLikeEBCDIC(buffer, read) == false) {
                return FileEncoding.BINARY;
            }
        } else {
            if (looksLikeANSI(buffer, read) == false) {
                return FileEncoding.BINARY;
            }
        }

        /*
         * If we got down here, we could not identify the file as certainly
         * binary by searching the first block of the file we read, so its
         * probably simple text. We should use the code default encoding for
         * this platform / user.
         *
         * This covers the case of an empty file, which VSS treats as a text
         * file in the default encoding, and so does TFS, so we should too.
         */
        return FileEncoding.getDefaultTextEncoding();
    } catch (final IOException e) {
        throw new TECoreException(e);
    } finally {
        if (stream != null) {
            IOUtils.closeSafely(stream);
        }
    }
}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.util.FileUtil.java

public static void createCompressedFiles(final List<String> fileNamesToBeCompressed,
        final String compressedFileName) throws IOException {

    final File compressedFile = new File(compressedFileName);
    for (final String fileNameToBeCompressed : fileNamesToBeCompressed) {
        final File fileToBeCompressed = new File(fileNameToBeCompressed);

        if (!fileToBeCompressed.exists()) {
            throw new IOException("Cache File does not exist: " + fileToBeCompressed.getPath());
        }/* w w w.  jav  a 2  s.c  om*/
    }
    final FileOutputStream outputFileStream = new FileOutputStream(compressedFile);
    final TarOutputStream tarStream = new TarOutputStream(new GZIPOutputStream(outputFileStream));
    try {
        for (final String fileNameToBeCompressed : fileNamesToBeCompressed) {
            final File fileToBeCompressed = new File(fileNameToBeCompressed);
            final String name = fileToBeCompressed.getName();
            final TarEntry tarAdd = new TarEntry(fileToBeCompressed);

            tarStream.setLongFileMode(TarOutputStream.LONGFILE_GNU);
            tarAdd.setModTime(fileToBeCompressed.lastModified());
            tarAdd.setName(name);
            tarStream.putNextEntry(tarAdd);

            FileInputStream inputStream = null;
            byte[] buffer = new byte[1024 * 64];
            try {

                inputStream = new FileInputStream(fileToBeCompressed);
                int nRead = inputStream.read(buffer, 0, buffer.length);
                while (nRead >= 0) {
                    tarStream.write(buffer, 0, nRead);
                    nRead = inputStream.read(buffer, 0, buffer.length);
                }

                tarStream.closeEntry();
            } finally {
                buffer = null;
                try {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                } catch (IOException ie) {
                    logger.error("Error closing I/O streams " + ie.toString());
                }
            }

        }
    } finally {
        if (tarStream != null) {
            tarStream.close();
        }

    }
}

From source file:net.grinder.util.LogCompressUtil.java

/**
 * Compress the given file./*  w w w .j a  va  2  s.  com*/
 * 
 * @param logFile
 *            file to be compressed
 * @return compressed file byte array
 */
public static byte[] compressFile(File logFile) {
    FileInputStream fio = null;
    ByteArrayOutputStream out = null;
    ZipOutputStream zos = null;
    try {
        fio = new FileInputStream(logFile);
        out = new ByteArrayOutputStream();
        zos = new ZipOutputStream(out);
        ZipEntry zipEntry = new ZipEntry("log.txt");
        zipEntry.setTime(new Date().getTime());
        zos.putNextEntry(zipEntry);
        byte[] buffer = new byte[COMPRESS_BUFFER_SIZE];
        int count = 0;
        while ((count = fio.read(buffer, 0, COMPRESS_BUFFER_SIZE)) != -1) {
            zos.write(buffer, 0, count);
        }
        zos.closeEntry();
        zos.finish();
        zos.flush();
        return out.toByteArray();
    } catch (IOException e) {
        LOGGER.error("Error occurs while compress {}", logFile.getAbsolutePath());
        LOGGER.error("Details", e);
        return null;
    } finally {
        IOUtils.closeQuietly(zos);
        IOUtils.closeQuietly(fio);
        IOUtils.closeQuietly(out);
    }
}

From source file:com.hipu.bdb.util.FileUtils.java

/**
 * @param f File to test.//  w ww .j  a v a  2s  . co  m
 * @return True if file is readable, has uncompressed extension,
 * and magic string at file start.
 * @exception IOException If file not readable or other problem.
 */
public static boolean isReadableWithExtensionAndMagic(final File f, final String uncompressedExtension,
        final String magic) throws IOException {
    boolean result = false;
    FileUtils.assertReadable(f);
    if (f.getName().toLowerCase().endsWith(uncompressedExtension)) {
        FileInputStream fis = new FileInputStream(f);
        try {
            byte[] b = new byte[magic.length()];
            int read = fis.read(b, 0, magic.length());
            fis.close();
            if (read == magic.length()) {
                StringBuffer beginStr = new StringBuffer(magic.length());
                for (int i = 0; i < magic.length(); i++) {
                    beginStr.append((char) b[i]);
                }

                if (beginStr.toString().equalsIgnoreCase(magic)) {
                    result = true;
                }
            }
        } finally {
            fis.close();
        }
    }

    return result;
}

From source file:gate.util.Files.java

/** Get a string representing the contents of a text file. */
public static String getString(File textFile) throws IOException {
    FileInputStream fis = new FileInputStream(textFile);
    int len = (int) textFile.length();
    byte[] textBytes = new byte[len];
    fis.read(textBytes, 0, len);
    fis.close();//from  w  w  w  .jav a  2  s .c om
    return new String(textBytes);
}

From source file:gate.util.Files.java

/** Get a byte array representing the contents of a binary file. */
public static byte[] getByteArray(File binaryFile) throws IOException {
    FileInputStream fis = new FileInputStream(binaryFile);
    int len = (int) binaryFile.length();
    byte[] bytes = new byte[len];
    fis.read(bytes, 0, len);
    fis.close();/*from   ww w  . j a  v  a  2  s  .  c o  m*/
    return bytes;
}

From source file:de.fhg.igd.mapviewer.server.file.FileTiler.java

/**
 * Creates a Jar archive that includes the given list of files
 * /*from www  .ja  v a  2  s.  c om*/
 * @param archiveFile the name of the jar archive file
 * @param tobeJared the files to be included in the jar file
 * 
 * @return if the operation was successful
 */
public static boolean createJarArchive(File archiveFile, List<File> tobeJared) {
    try {
        byte buffer[] = new byte[BUFFER_SIZE];
        // Open archive file
        FileOutputStream stream = new FileOutputStream(archiveFile);
        JarOutputStream out = new JarOutputStream(stream, new Manifest());

        for (int i = 0; i < tobeJared.size(); i++) {
            if (tobeJared.get(i) == null || !tobeJared.get(i).exists() || tobeJared.get(i).isDirectory())
                continue; // Just in case...
            log.debug("Adding " + tobeJared.get(i).getName());

            // Add archive entry
            JarEntry jarAdd = new JarEntry(tobeJared.get(i).getName());
            jarAdd.setTime(tobeJared.get(i).lastModified());
            out.putNextEntry(jarAdd);

            // Write file to archive
            FileInputStream in = new FileInputStream(tobeJared.get(i));
            while (true) {
                int nRead = in.read(buffer, 0, buffer.length);
                if (nRead <= 0)
                    break;
                out.write(buffer, 0, nRead);
            }
            in.close();
        }

        out.close();
        stream.close();
        log.info("Adding completed OK");
        return true;
    } catch (Exception e) {
        log.error("Creating jar file failed", e);
        return false;
    }
}

From source file:com.yoctopuce.YoctoAPI.YFirmwareUpdate.java

private static YFirmwareFile _loadFirmwareFile(File file) throws YAPI_Exception {
    FileInputStream in = null;
    try {//from www. j a  v  a  2 s.  com
        in = new FileInputStream(file);
    } catch (FileNotFoundException e) {
        throw new YAPI_Exception(YAPI.FILE_NOT_FOUND, "File not found");
    }
    ByteArrayOutputStream result = new ByteArrayOutputStream(1024);

    try {
        byte[] buffer = new byte[1024];
        int readed = 0;
        while (readed >= 0) {
            readed = in.read(buffer, 0, buffer.length);
            if (readed < 0) {
                // end of connection
                break;
            } else {
                result.write(buffer, 0, readed);
            }
        }

    } catch (IOException e) {
        throw new YAPI_Exception(YAPI.IO_ERROR, "unable to load file :" + e.getLocalizedMessage());
    } finally {
        try {
            in.close();
        } catch (IOException ignore) {
        }
    }

    return YFirmwareFile.Parse(file.getPath(), result.toByteArray());
}

From source file:net.grinder.util.LogCompressUtil.java

/**
 * Compress multiple Files.// w  ww.  j a v  a 2 s  .  c  om
 * 
 * @param logFiles
 *            files to be compressed
 * @return compressed file byte array
 */
public static byte[] compressFile(File[] logFiles) {
    FileInputStream fio = null;
    ByteArrayOutputStream out = null;
    ZipOutputStream zos = null;
    try {

        out = new ByteArrayOutputStream();
        zos = new ZipOutputStream(out);
        for (File each : logFiles) {
            try {
                fio = new FileInputStream(each);
                ZipEntry zipEntry = new ZipEntry(each.getName());
                zipEntry.setTime(each.lastModified());
                zos.putNextEntry(zipEntry);
                byte[] buffer = new byte[COMPRESS_BUFFER_SIZE];
                int count = 0;
                while ((count = fio.read(buffer, 0, COMPRESS_BUFFER_SIZE)) != -1) {
                    zos.write(buffer, 0, count);
                }
                zos.closeEntry();
            } catch (IOException e) {
                LOGGER.error("Error occurs while compress {}", each.getAbsolutePath());
                LOGGER.error("Details", e);
            } finally {
                IOUtils.closeQuietly(fio);
            }
        }
        zos.finish();
        zos.flush();
        return out.toByteArray();
    } catch (IOException e) {
        LOGGER.info("Error occurs while compress log : {} ", e.getMessage());
        LOGGER.debug("Details", e);
        return null;
    } finally {
        IOUtils.closeQuietly(zos);
        IOUtils.closeQuietly(fio);
        IOUtils.closeQuietly(out);
    }
}

From source file:net.filterlogic.util.imaging.ToTIFF.java

/**
 * Load file into a byte array.//from   w  w w .j  ava  2  s . c  o m
 * @param fileName
 * @return byte array
 */
public static byte[] loadFileToByteArray(String fileName) {
    FileInputStream fis;

    try {
        fis = new FileInputStream(fileName);

        int fisSize = fis.available();

        byte[] in = new byte[fisSize];

        // read entire file
        fis.read(in, 0, fisSize);

        fis.close();

        return in;
    } catch (Exception fioe) {
        System.out.println(fioe.toString());
        return null;
    }
}