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.EncryptionUtils.java

public static String getMD5Sum(File file) {
    try {//from  w ww . jav a  2  s .  co m
        FileInputStream fileInputStream = new FileInputStream(file);
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] bytes = new byte[2048];
        int readBytes;

        while ((readBytes = fileInputStream.read(bytes)) != -1) {
            md5.update(bytes, 0, readBytes);
        }

        return new String(Hex.encodeHex(md5.digest()));

    } catch (Exception e) {
        Log_OC.e(TAG, e.getMessage());
    }

    return "";
}

From source file:com.muzima.controller.FormController.java

private static String getStringMedia(String mediaUri) {
    String mediaString = null;//ww w.  j a v  a 2 s  .co  m
    if (!StringUtils.isEmpty(mediaUri)) {
        //fetch the media and convert it to @Base64 encoded string.
        File f = new File(mediaUri);
        if (f.exists()) {

            // here the media file is encrypted so we decrypt it
            EnDeCrypt.decrypt(f, "this-is-supposed-to-be-a-secure-key");

            try {
                FileInputStream fis = new FileInputStream(f);
                byte[] fileBytes = new byte[(int) f.length()];
                fis.read(fileBytes);

                //convert the decrypted media to Base64 string
                mediaString = MediaUtils.toBase64(fileBytes);
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }

            // and encrypt again
            EnDeCrypt.encrypt(f, "this-is-supposed-to-be-a-secure-key");
        }
    }
    return mediaString != null ? mediaString : mediaUri;
}

From source file:com.wattzap.model.social.SelfLoopsAPI.java

public static int uploadActivity(String email, String passWord, String fileName, String note)
        throws IOException {
    JSONObject jsonObj = null;/*from   w  w  w.  j a v a2s  .  c o m*/

    FileInputStream in = null;
    GZIPOutputStream out = null;
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("enctype", "multipart/mixed");

        in = new FileInputStream(fileName);
        // Create stream to compress data and write it to the to file.
        ByteArrayOutputStream obj = new ByteArrayOutputStream();
        out = new GZIPOutputStream(obj);

        // Copy bytes from one stream to the other
        byte[] buffer = new byte[4096];
        int bytes_read;
        while ((bytes_read = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytes_read);
        }
        out.close();
        in.close();

        ByteArrayBody bin = new ByteArrayBody(obj.toByteArray(), ContentType.create("application/x-gzip"),
                fileName);
        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("email", new StringBody(email, ContentType.TEXT_PLAIN))
                .addPart("pw", new StringBody(passWord, ContentType.TEXT_PLAIN)).addPart("tcxfile", bin)
                .addPart("note", new StringBody(note, ContentType.TEXT_PLAIN)).build();

        httpPost.setEntity(reqEntity);

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            int code = response.getStatusLine().getStatusCode();
            switch (code) {
            case 200:

                HttpEntity respEntity = response.getEntity();

                if (respEntity != null) {
                    // EntityUtils to get the response content
                    String content = EntityUtils.toString(respEntity);
                    //System.out.println(content);
                    JSONParser jsonParser = new JSONParser();
                    jsonObj = (JSONObject) jsonParser.parse(content);
                }

                break;
            case 403:
                throw new RuntimeException(
                        "Authentification failure " + email + " " + response.getStatusLine());
            default:
                throw new RuntimeException("Error " + code + " " + response.getStatusLine());
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (response != null) {
                response.close();
            }
        }

        int activityId = ((Long) jsonObj.get("activity_id")).intValue();

        // parse error code
        int error = ((Long) jsonObj.get("error_code")).intValue();
        if (activityId == -1) {
            String message = (String) jsonObj.get("message");
            switch (error) {
            case 102:
                throw new RuntimeException("Empty TCX file " + fileName);
            case 103:
                throw new RuntimeException("Invalide TCX Format " + fileName);
            case 104:
                throw new RuntimeException("TCX Already Present " + fileName);
            case 105:
                throw new RuntimeException("Invalid XML " + fileName);
            case 106:
                throw new RuntimeException("invalid compression algorithm");
            case 107:
                throw new RuntimeException("Invalid file mime types");
            default:
                throw new RuntimeException(message + " " + error);
            }
        }

        return activityId;
    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
        httpClient.close();
    }
}

From source file:uploadProcess.java

public static boolean decrypt(File inputFolder, String fileName, String patientID) {
    try {//from   ww  w . j av a 2s .c  om
        //Download File from Cloud..
        DropboxUpload download = new DropboxUpload();
        download.downloadFile(fileName, StoragePath.getDropboxDir() + patientID, inputFolder);

        String ukey = GetKey.getPatientKey(patientID);
        File inputFile = new File(inputFolder.getAbsolutePath() + File.separator + fileName);
        FileInputStream fis = new FileInputStream(inputFile);
        File outputFolder = new File(inputFolder.getAbsolutePath() + File.separator + "temp");
        if (!outputFolder.exists()) {
            outputFolder.mkdir();
        }
        FileOutputStream fos = new FileOutputStream(outputFolder.getAbsolutePath() + File.separator + fileName);
        byte[] k = ukey.getBytes();
        SecretKeySpec key = new SecretKeySpec(k, "AES");
        Cipher enc = Cipher.getInstance("AES");
        enc.init(Cipher.DECRYPT_MODE, key);
        CipherOutputStream cos = new CipherOutputStream(fos, enc);
        byte[] buf = new byte[1024];
        int read;
        while ((read = fis.read(buf)) != -1) {
            cos.write(buf, 0, read);
        }
        fis.close();
        fos.flush();
        cos.close();
        return true;
    } catch (Exception e) {
        System.out.println("Error: " + e);
    }
    return false;
}

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

public static File deflate(final File outputDir, final File zipFile, final File[] files, boolean overwrite) {

    if (zipFile.exists() && overwrite) {
        if (LOGGER.isInfoEnabled())
            LOGGER.info("The output file already exists: " + zipFile + " overvriting");
        return zipFile;
    }/*from   ww  w . j  a  v  a  2s. co m*/

    // Create a buffer for reading the files
    byte[] buf = new byte[Conf.getBufferSize()];

    ZipOutputStream out = null;
    BufferedOutputStream bos = null;
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(zipFile);
        bos = new BufferedOutputStream(fos);
        out = new ZipOutputStream(bos);

        // Compress the files
        for (File file : files) {
            FileInputStream in = null;
            try {
                in = new FileInputStream(file);
                if (file.isDirectory()) {
                    continue;
                } else {
                    // Add ZIP entry to output stream.
                    out.putNextEntry(new ZipEntry(file.getName()));
                    // Transfer bytes from the file to the ZIP file
                    int len;
                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                    out.flush();
                }

            } finally {
                try {
                    // Complete the entry
                    out.closeEntry();
                } catch (Exception e) {
                }
                IOUtils.closeQuietly(in);
            }

        }

    } catch (IOException e) {
        LOGGER.error(e.getLocalizedMessage(), e);
        return null;
    } finally {

        // Complete the ZIP file
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(bos);
        IOUtils.closeQuietly(fos);
    }

    return zipFile;
}

From source file:SystemUtils.java

public static void CopyFile(String src, String dest) throws IOException {
    FileInputStream fis = null;
    FileOutputStream fos = null;/*  w w  w.ja  v  a  2s.co  m*/
    byte[] buf;
    int len;

    try {
        fis = new FileInputStream(src);
        fos = new FileOutputStream(dest);

        buf = new byte[2048];

        len = fis.read(buf);
        while (len != -1) {
            fos.write(buf, 0, len);
            len = fis.read(buf);
        }
    } //End try block
    finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (Exception e) {
            }
        }

        if (fos != null) {
            try {
                fos.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:com.collabnet.ccf.pi.qc.v90.QCGAHelper.java

/**
 * Copy a file from origin to target//from   w  ww .j av a 2 s.  co m
 * 
 * @param origin
 *            origin file
 * @param target
 *            target file
 */
public static void copyFile(File origin, File target) {
    try {
        FileInputStream fis = new FileInputStream(origin);
        FileOutputStream fos = new FileOutputStream(target);
        int readCount = 0;
        byte[] tmpData = new byte[1024 * 4];
        while ((readCount = fis.read(tmpData)) != -1) {
            fos.write(tmpData, 0, readCount);
        }
        fis.close();
        fos.close();
    } catch (FileNotFoundException e) {
        String message = "Could not read attachment content." + " File not found " + origin.getAbsolutePath();
        log.error(message, e);
        throw new CCFRuntimeException(message, e);
    } catch (IOException e) {
        String message = "Could not read attachment content." + " IOException while reading "
                + origin.getAbsolutePath();
        log.error(message, e);
        throw new CCFRuntimeException(message, e);
    }
}

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

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

    FileInputStream in = null;

    try {//from w  ww .j a  v  a  2s  .com

        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) {
        throw error;
    } finally {

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

From source file:de.ingrid.interfaces.csw.tools.FileUtils.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.//from w  w  w.  ja v  a2  s  .  c o  m
 * 
 * @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.
 * 
 *             Source: http://www.dreamincode.net/code/snippet1443.htm
 */
public static void copyRecursive(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 (String element : list) {
            File dest1 = new File(dest, element);
            File src1 = new File(src, element);
            copyRecursive(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);
            }
            fin.close();
            fout.close();
            fin = null;
            fout = null;
        } 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) {
                fin.close();
            }
        }
    }
}

From source file:net.sf.jasperreports.engine.util.JRLoader.java

/**
 *
 *//*  w ww.  java2s  . co  m*/
public static byte[] loadBytes(File file) throws JRException {
    ByteArrayOutputStream baos = null;
    FileInputStream fis = null;

    try {
        fis = new FileInputStream(file);
        baos = new ByteArrayOutputStream();

        byte[] bytes = new byte[10000];
        int ln = 0;
        while ((ln = fis.read(bytes)) > 0) {
            baos.write(bytes, 0, ln);
        }

        baos.flush();
    } catch (IOException e) {
        throw new JRException(EXCEPTION_MESSAGE_KEY_BYTE_DATA_LOADING_ERROR, new Object[] { file }, e);
    } finally {
        if (baos != null) {
            try {
                baos.close();
            } catch (IOException e) {
            }
        }

        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
            }
        }
    }

    return baos.toByteArray();
}