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:com.android.dumprendertree2.FsUtils.java

public static byte[] readDataFromStorage(File file) {
    if (!file.exists()) {
        Log.d(LOG_TAG, "readDataFromStorage(): File does not exist: " + file.getAbsolutePath());
        return null;
    }/*from  ww w.  ja va2 s.com*/

    byte[] bytes = null;
    try {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            bytes = new byte[(int) file.length()];
            fis.read(bytes);
        } finally {
            if (fis != null) {
                fis.close();
            }
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "file.getAbsolutePath=" + file.getAbsolutePath(), e);
    }

    return bytes;
}

From source file:de.bps.onyx.util.SummaryCheckSumValidator.java

/**
 * Validates the Onyx test result summary pages checksum.
 * //from   ww w .  j av  a  2  s .  c o  m
 * @param file
 *            The file containing the summary HTML
 * @return SummaryChecksumValidatorResult structure. The contained validated
 *         field contains the validation result.
 * 
 * @see SummaryChecksumValidatorResult
 */
public static SummaryChecksumValidatorResult validate(final File file) {
    FileInputStream fis = null;
    final ByteArrayOutputStream baos = new ByteArrayOutputStream((int) file.length());
    try {
        fis = new FileInputStream(file);
        final byte[] buf = new byte[102400];
        int read = 0;
        while ((read = fis.read(buf)) >= 0) {
            baos.write(buf, 0, read);
        }
    } catch (final IOException e) {
        //         log.error("Error reading file to validate: " + file.getAbsolutePath(), e);
        final SummaryChecksumValidatorResult result = new SummaryChecksumValidatorResult();
        result.result = "onyx.summary.validation.result.error.reading.file";
        result.info = file.getAbsolutePath() + " - " + e.getMessage();
        return result;

    } finally {
        try {
            if (fis != null) {
                fis.close();
                fis = null;
            }
        } catch (final Exception e) {
            // ignore
        }
    }

    try {
        baos.flush();
    } catch (final IOException e) {
        // ignore
    }

    final String html = baos.toString();

    try {
        baos.close();
    } catch (final IOException e) {
        // ignore
    }

    return internalValidate(html);
}

From source file:com.sinpo.xnfc.nfc.Util.java

public static String readFileSdcardFile(String fileName) throws IOException {
    String res = "";
    try {// w  w w.j  a va2s .  c  o m
        FileInputStream fin = new FileInputStream(fileName);

        int length = fin.available();

        byte[] buffer = new byte[length];
        fin.read(buffer);

        res = EncodingUtils.getString(buffer, "UTF-8");

        fin.close();
    }

    catch (Exception e) {
        e.printStackTrace();
    }
    return res;
}

From source file:com.intuit.s3encrypt.S3Encrypt.java

public static KeyPair loadKeyPair(String filename, String algorithm)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    // Read public key from file.
    FileInputStream keyfis = new FileInputStream(filename + ".pub");
    byte[] encodedPublicKey = new byte[keyfis.available()];
    keyfis.read(encodedPublicKey);
    keyfis.close();//ww  w  . j  av a 2s .c  o  m

    // Read private key from file.
    keyfis = new FileInputStream(filename);
    byte[] encodedPrivateKey = new byte[keyfis.available()];
    keyfis.read(encodedPrivateKey);
    keyfis.close();

    // Generate KeyPair from public and private keys.
    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    return new KeyPair(publicKey, privateKey);

}

From source file:com.enderville.enderinstaller.util.InstallScript.java

/**
 * Repackages all the files in the tmp directory to the new minecraft.jar
 *
 * @param tmp The temp directory where mods were installed.
 * @param mcjar The location to save the new minecraft.jar.
 * @throws IOException/*from  w  w w .  j  a v a  2s. c  o m*/
 */
public static void repackMCJar(File tmp, File mcjar) throws IOException {
    byte[] dat = new byte[4 * 1024];

    JarOutputStream jarout = new JarOutputStream(FileUtils.openOutputStream(mcjar));

    Queue<File> queue = new LinkedList<File>();
    for (File f : tmp.listFiles()) {
        queue.add(f);
    }

    while (!queue.isEmpty()) {
        File f = queue.poll();
        if (f.isDirectory()) {
            for (File child : f.listFiles()) {
                queue.add(child);
            }
        } else {
            //TODO need a better way to do this
            String name = f.getPath().substring(tmp.getPath().length() + 1);
            //TODO is this formatting really required for jars?
            name = name.replace("\\", "/");
            if (f.isDirectory() && !name.endsWith("/")) {
                name = name + "/";
            }
            JarEntry entry = new JarEntry(name);
            jarout.putNextEntry(entry);

            FileInputStream in = new FileInputStream(f);
            int len = -1;
            while ((len = in.read(dat)) > 0) {
                jarout.write(dat, 0, len);
            }
            in.close();
        }
        jarout.closeEntry();
    }
    jarout.close();

}

From source file:com.pieframework.runtime.utils.Zipper.java

public static void zip(String zipFile, Map<String, File> flist) {
    byte[] buf = new byte[1024];
    try {// w  w w  .j  a v  a 2  s .  c  o m
        // Create the ZIP file 
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));

        // Compress the files 
        for (String url : flist.keySet()) {
            FileInputStream in = new FileInputStream(flist.get(url).getPath());
            // Add ZIP entry to output stream. Zip entry should be relative
            out.putNextEntry(new ZipEntry(url));
            // Transfer bytes from the file to the ZIP file 
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            // Complete the entry 
            out.closeEntry();
            in.close();
        }

        // Complete the ZIP file 
        out.close();
    } catch (Exception e) {
        throw new RuntimeException("Encountered errors zipping file " + zipFile, e);
    }
}

From source file:Main.java

public static void compressFile(String inputFilePath, boolean deleteSource) throws IOException {
    byte[] buffer = new byte[1024];
    FileOutputStream fos = null;/*w  w  w  .j a  va 2s  .c o m*/
    GZIPOutputStream gzos = null;
    FileInputStream fis = null;

    try {
        fos = new FileOutputStream(inputFilePath + ".gz");
        gzos = new GZIPOutputStream(fos);

        fis = new FileInputStream(inputFilePath);
        //         String zipEntryName = inputFilePath.substring(inputFilePath.lastIndexOf(File.separator) + 1);         
        //         gzos.putNextEntry(new ZipEntry(zipEntryName));

        int length;
        while ((length = fis.read(buffer)) > 0) {
            gzos.write(buffer, 0, length);
        }
    } finally {
        gzos.close();
        fos.close();
        fis.close();
    }

    if (deleteSource) {
        new File(inputFilePath).delete();
    }
}

From source file:de.flapdoodle.embed.process.io.file.Files.java

private static void copyFile(File source, File destination) throws IOException {
    FileInputStream reader = null;
    FileOutputStream writer = null;
    try {// ww w.  j ava 2s . co  m
        reader = new FileInputStream(source);
        writer = new FileOutputStream(destination);

        int read;
        byte[] buf = new byte[BYTE_BUFFER_LENGTH];
        while ((read = reader.read(buf)) != -1) {
            writer.write(buf, 0, read);
        }

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

From source file:ch.admin.suis.msghandler.util.ZipUtils.java

/**
 * Creates a new unique ZIP file in the destination directory and adds to it
 * the provided collection of files./*w w  w .ja va2  s .  co m*/
 *
 * @param toDir The name of the file created
 * @param files The files to compress
 * @return A Zipped File
 * @throws IOException if the file cannot be created because of a IO error
 */
public static File compress(File toDir, Collection<File> files) throws IOException {
    final File zipFile = File.createTempFile("data", ".zip", toDir);

    // was there an exception?
    boolean exceptionThrown = false;

    try (ZipOutputStream zout = new ZipOutputStream(
            new BufferedOutputStream(new FileOutputStream(zipFile), BUFFER_SIZE))) {

        byte[] data = new byte[BUFFER_SIZE];

        for (File file : files) {
            // create the entry
            zout.putNextEntry(new ZipEntry(file.getName()));

            FileInputStream in = new FileInputStream(file);

            try (FileLock lock = in.getChannel().tryLock(0, Long.MAX_VALUE, true)) {
                isInValid(lock, in);
                int len;

                // write the file to the entry
                while ((len = in.read(data)) > 0) {
                    zout.write(data, 0, len);
                }
                lock.release();
            } finally {
                try {
                    in.close();
                } catch (IOException e) {
                    LOG.error("cannot properly close the opened file " + file.getAbsolutePath(), e);
                }
            }

        }
    } catch (IOException e) {
        LOG.error("error while creating the ZIP file " + zipFile.getAbsolutePath(), e);
        // mark for the finally block
        exceptionThrown = true;
        // rethrow - the finally block is only for the first exception
        throw e;
    } finally {
        // remove the file in case of an exception
        if (exceptionThrown && !zipFile.delete()) {
            LOG.error("cannot delete the file " + zipFile.getAbsolutePath());
        }
    }

    return zipFile;
}

From source file:Main.java

public static String compressGzipFile(String filename) {
    if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {

        File flockedFilesFolder = new File(
                Environment.getExternalStorageDirectory() + File.separator + "FlockLoad");
        System.out.println("FlockedFileDir: " + flockedFilesFolder);
        String uncompressedFile = flockedFilesFolder.toString() + "/" + filename;
        String compressedFile = flockedFilesFolder.toString() + "/" + "gzip.zip";

        try {/*from  www  .  j  ava 2  s  .  co m*/
            FileInputStream fis = new FileInputStream(uncompressedFile);
            FileOutputStream fos = new FileOutputStream(compressedFile);
            GZIPOutputStream gzipOS = new GZIPOutputStream(fos) {
                {
                    def.setLevel(Deflater.BEST_COMPRESSION);
                }
            };

            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                gzipOS.write(buffer, 0, len);
            }
            //close resources
            gzipOS.close();
            fos.close();
            fis.close();
            return compressedFile;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;

}