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.owncloud.android.utils.PushUtils.java

public static Key readKeyFromFile(boolean readPublicKey) {
    String keyPath = MainApp.getStoragePath() + File.separator + MainApp.getDataFolder() + File.separator
            + KEYPAIR_FOLDER;/*  w  w  w  . j  a  va 2  s.c  o m*/

    String privateKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PRIV_EXTENSION;
    String publicKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PUB_EXTENSION;

    String path;

    if (readPublicKey) {
        path = publicKeyPath;
    } else {
        path = privateKeyPath;
    }

    FileInputStream fileInputStream = null;
    try {
        fileInputStream = new FileInputStream(path);
        byte[] bytes = new byte[fileInputStream.available()];
        fileInputStream.read(bytes);
        fileInputStream.close();

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        if (readPublicKey) {
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
            return keyFactory.generatePublic(keySpec);
        } else {
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
            return keyFactory.generatePrivate(keySpec);
        }

    } catch (FileNotFoundException e) {
        Log_OC.d(TAG, "Failed to find path while reading the Key");
    } catch (IOException e) {
        Log_OC.d(TAG, "IOException while reading the key");
    } catch (InvalidKeySpecException e) {
        Log_OC.d(TAG, "InvalidKeySpecException while reading the key");
    } catch (NoSuchAlgorithmException e) {
        Log_OC.d(TAG, "RSA algorithm not supported");
    }

    return null;
}

From source file:com.pclinuxos.rpm.util.FileUtils.java

/**
 * The method copies a file to an other location. 
 * //  w  ww  .  j  ava2s .co m
 * @param source file/folder to copy
 * @param dest destination file/folder
 * @return 0 if copying was successfully, 1 if the source file/folder does not exist, 2 if a IOException
 * occurred while copying.
 */
public static byte cp(File source, File dest) {

    byte returnCode = 0;

    try {

        FileInputStream sourceIn = new FileInputStream(source);
        FileOutputStream destOut = new FileOutputStream(dest);

        if (!source.exists()) {

            returnCode = 1;
        }

        // 64kb buffer
        byte[] buffer = new byte[0xFFFF];

        while (sourceIn.read(buffer) != -1) {

            destOut.write(buffer);
        }

        sourceIn.close();
        destOut.flush();
        destOut.close();

    } catch (FileNotFoundException e) {

        returnCode = 1;

    } catch (IOException e) {

        returnCode = 2;
    }

    return returnCode;
}

From source file:com.ecofactor.qa.automation.platform.util.FileUtil.java

/**
 * Adds the file to zip./*from w  w  w.  jav a  2s .c om*/
 * @param path the path
 * @param srcFile the src file
 * @param zip the zip
 */
private static void addFileToZip(final String path, final String srcFile, final ZipOutputStream zip) {

    try {
        final File folder = new File(srcFile);
        if (folder.isDirectory()) {
            addFolderToZip(path, srcFile, zip);
        } else {
            final byte[] buf = new byte[1024];
            int len;
            final FileInputStream inputStream = new FileInputStream(srcFile);
            zip.putNextEntry(
                    new ZipEntry(new StringBuilder(path).append(SLASH).append(folder.getName()).toString()));
            do {
                len = inputStream.read(buf);
                zip.write(buf, 0, len);
            } while (len > 0);
            inputStream.close();
        }
    } catch (IOException e) {
        LOGGER.error("Error in add flies to zip", e);
    }
}

From source file:FileTools.java

/** copie le fichier source dans le fichier resultat
 * retourne vrai si cela russit/*from w  w  w . j  av a2s .  c  o m*/
 */
public static boolean copyFile(File source, File dest) {
    try {
        // Declaration et ouverture des flux
        java.io.FileInputStream sourceFile = new java.io.FileInputStream(source);

        try {
            java.io.FileOutputStream destinationFile = null;

            try {
                destinationFile = new FileOutputStream(dest);

                // Lecture par segment de 0.5Mo
                byte buffer[] = new byte[512 * 1024];
                int nbLecture;

                while ((nbLecture = sourceFile.read(buffer)) != -1) {
                    destinationFile.write(buffer, 0, nbLecture);
                }
            } finally {
                destinationFile.close();
            }
        } finally {
            sourceFile.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
        return false; // Erreur
    }

    return true; // Rsultat OK
}

From source file:com.juancarlosroot.threads.SimulatedUser.java

public static void addToZipFile(String fileName, ZipOutputStream zos)
        throws FileNotFoundException, IOException {
    File file = new File(fileName);
    FileInputStream fis = new FileInputStream(file);
    ZipEntry zipEntry = new ZipEntry(fileName);
    zos.putNextEntry(zipEntry);/*from   w ww . j  a  v  a  2  s .  c o m*/

    byte[] bytes = new byte[2048];
    int length;
    while ((length = fis.read(bytes)) >= 0) {
        zos.write(bytes, 0, length);
    }

    zos.closeEntry();
    fis.close();
}

From source file:mtmo.test.mediadrm.Utils.java

public static byte[] readActionTokenFromFile(String path) {
    StringBuilder builder = new StringBuilder();
    FileInputStream fis = null;
    byte[] buff = new byte[1024];
    int ret = 0;// www .j av  a 2s.c  om
    File file = null;

    if (path.isEmpty()) {
        return null;
    }

    file = new File(path);
    if (!file.exists()) {
        return null;
    }

    try {
        fis = new FileInputStream(file);
        while ((ret = fis.read(buff)) > 0) {
            builder.append(new String(buff, 0, ret));
        }
    } catch (IOException e) {
        return null;
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
            }
            fis = null;
        }
    }
    return builder.toString().getBytes();
}

From source file:au.org.ands.vocabs.toolkit.utils.ToolkitFileUtils.java

/** Add a file to a ZIP archive.
 * @param zos The ZipOutputStream representing the ZIP archive.
 * @param file The File which is to be added to the ZIP archive.
 * @return True if adding succeeded./*w  w  w .  j  a  v a2s .co  m*/
 * @throws IOException Any exception when reading/writing data.
 */
private static boolean zipFile(final ZipOutputStream zos, final File file) throws IOException {
    if (!file.canRead()) {
        logger.error("zipFile can not read " + file.getCanonicalPath());
        return false;
    }
    zos.putNextEntry(new ZipEntry(file.getName()));
    FileInputStream fis = new FileInputStream(file);

    byte[] buffer = new byte[BUFFER_SIZE];
    int byteCount = 0;
    while ((byteCount = fis.read(buffer)) != -1) {
        zos.write(buffer, 0, byteCount);
    }
    fis.close();
    zos.closeEntry();
    return true;
}

From source file:Main.java

private static void addFileToZip(String sourceFolderPath, String sourceFilePath, String baseFolderPath,
        ZipOutputStream zos) throws Exception {

    File item = new File(sourceFilePath);
    if (item == null || !item.exists())
        return; //skip if the file is not exist
    if (isSymLink(item))
        return; // do nothing to symbolic links.

    if (baseFolderPath == null)
        baseFolderPath = "";

    if (item.isDirectory()) {
        for (String subItem : item.list()) {
            addFileToZip(sourceFolderPath + File.separator + item.getName(),
                    sourceFilePath + File.separator + subItem, baseFolderPath, zos);
        }//from  w  w w  .j  a  v a  2 s.  c  o m
    } else {
        byte[] buf = new byte[102400]; //100k buffer
        int len;
        FileInputStream inStream = new FileInputStream(sourceFilePath);
        if (baseFolderPath.equals("")) //sourceFiles in absolute path, zip the file with absolute path
            zos.putNextEntry(new ZipEntry(sourceFilePath));
        else {//relative path
            String relativePath = sourceFilePath.substring(baseFolderPath.length());
            zos.putNextEntry(new ZipEntry(relativePath));
        }

        while ((len = inStream.read(buf)) > 0) {
            zos.write(buf, 0, len);
        }

    }
}

From source file:com.jaspersoft.studio.community.utils.CommunityAPIUtils.java

/**
 * Creates a ZIP file using the specified zip entries.
 * /*from   w ww  .  j a v  a2  s .c  om*/
 * @param zipEntries the list of entries that will end up in the final zip file
 * @return the zip file reference
 * @throws CommunityAPIException
 */
public static File createZipFile(List<ZipEntry> zipEntries) throws CommunityAPIException {
    String tmpDirectory = System.getProperty("java.io.tmpdir"); //$NON-NLS-1$
    String zipFileLocation = tmpDirectory;
    if (!(tmpDirectory.endsWith("/") || tmpDirectory.endsWith("\\"))) { //$NON-NLS-1$ //$NON-NLS-2$
        zipFileLocation += System.getProperty("file.separator"); //$NON-NLS-1$
    }
    zipFileLocation += "issueDetails.zip"; //$NON-NLS-1$

    try {
        // create byte buffer
        byte[] buffer = new byte[1024];
        // create object of FileOutputStream
        FileOutputStream fout = new FileOutputStream(zipFileLocation);
        // create object of ZipOutputStream from FileOutputStream
        ZipOutputStream zout = new ZipOutputStream(fout);

        for (ZipEntry ze : zipEntries) {
            //create object of FileInputStream for source file
            FileInputStream fin = new FileInputStream(ze.getLocation());
            zout.putNextEntry(new java.util.zip.ZipEntry(ze.getLocation()));
            // After creating entry in the zip file, actually write the file.
            int length;
            while ((length = fin.read(buffer)) > 0) {
                zout.write(buffer, 0, length);
            }
            //close the zip entry and related InputStream
            zout.closeEntry();
            fin.close();
        }
        //close the ZipOutputStream
        zout.close();
    } catch (IOException e) {
        throw new CommunityAPIException(Messages.CommunityAPIUtils_ZipCreationError, e);
    }
    return new File(zipFileLocation);
}

From source file:br.com.manish.ahy.kernel.util.FileUtil.java

public static void copyFile(String from, String to, Boolean overwrite) {

    try {//  w  w w.  j  a  va  2  s  .  c om
        File fromFile = new File(from);
        File toFile = new File(to);

        if (!fromFile.exists()) {
            throw new IOException("File not found: " + from);
        }
        if (!fromFile.isFile()) {
            throw new IOException("Can't copy directories: " + from);
        }
        if (!fromFile.canRead()) {
            throw new IOException("Can't read file: " + from);
        }

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

        if (toFile.exists() && !overwrite) {
            throw new IOException("File already exists.");
        } else {
            String parent = toFile.getParent();
            if (parent == null) {
                parent = System.getProperty("user.dir");
            }
            File dir = new File(parent);
            if (!dir.exists()) {
                throw new IOException("Destination directory does not exist: " + parent);
            }
            if (dir.isFile()) {
                throw new IOException("Destination is not a valid directory: " + parent);
            }
            if (!dir.canWrite()) {
                throw new IOException("Can't write on destination: " + parent);
            }
        }

        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {

            fis = new FileInputStream(fromFile);
            fos = new FileOutputStream(toFile);
            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }

        } finally {
            if (from != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    log.error(e);
                }
            }
            if (to != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    log.error(e);
                }
            }
        }

    } catch (Exception e) {
        throw new OopsException(e, "Problems when copying file.");
    }
}