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:uploadProcess.java

public static boolean encrypt(File inputFolder, File outputFolder, String fileName, String patientID) {
    try {//w  w  w  .j  a va  2  s.co  m

        String ukey = GetKey.getPatientKey(patientID);
        File filePath = new File(inputFolder.getAbsolutePath() + File.separator + fileName);
        FileInputStream fis = new FileInputStream(filePath);
        File outputFile = new File(outputFolder.getAbsolutePath() + File.separator + fileName);
        FileOutputStream fos = new FileOutputStream(outputFile);
        byte[] k = ukey.getBytes();
        SecretKeySpec key = new SecretKeySpec(k, "AES");
        //            System.out.println(key);
        Cipher enc = Cipher.getInstance("AES");
        enc.init(Cipher.ENCRYPT_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();

        //Upload File to cloud
        DropboxUpload upload = new DropboxUpload();
        upload.uploadFile(outputFolder, fileName, StoragePath.getDropboxDir() + patientID);
        DeleteDirectory.delete(outputFolder);
        return true;
    } catch (Exception e) {
        System.out.println("Error: " + e);
    }
    return false;
}

From source file:com.polyvi.xface.util.XFileUtils.java

/**
 * ??/*w  ww  . ja v  a 2 s  .  co  m*/
 *
 * @param filePath
 *            ?
 * @return ??
 */
public static String readFileContent(String filePath) {
    if (null == filePath) {
        return null;
    }
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        FileInputStream fis = new FileInputStream(filePath);

        byte[] buffer = new byte[XConstant.BUFFER_LEN];
        int len = 0;
        while ((len = fis.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }

        String content = bos.toString();
        bos.close();
        fis.close();
        return content;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:eu.planets_project.tb.impl.data.util.DataHandlerImpl.java

public static String encodeToBase64ByteArrayString(File src) throws IOException {
    byte[] b = new byte[(int) src.length()];
    FileInputStream fis = null;
    try {/*from www  . j  av  a2s .  c o  m*/
        fis = new FileInputStream(src);
        fis.read(b);
    } catch (IOException e) {
        throw e;
    } finally {
        fis.close();
    }

    //encode String
    return Base64.encodeBase64(b).toString();
}

From source file:graphene.util.fs.FileUtils.java

public static void copyFile(final File srcFile, final File dstFile) throws IOException {
        // noinspection ResultOfMethodCallIgnored
        dstFile.getParentFile().mkdirs();
        FileInputStream input = null;
        FileOutputStream output = null;
        try {//from ww  w.ja va  2s.  c  om
            input = new FileInputStream(srcFile);
            output = new FileOutputStream(dstFile);
            final int bufferSize = 1024;
            final byte[] buffer = new byte[bufferSize];
            int bytesRead;
            while ((bytesRead = input.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
            }
        } catch (final IOException e) {
            // Because the message from this cause may not mention which file
            // it's about
            throw new IOException("Could not copy '" + srcFile + "' to '" + dstFile + "'", e);
        } finally {
            if (input != null) {
                input.close();
            }
            if (output != null) {
                output.close();
            }
        }
    }

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

protected static void workaroundCopyFile(final File src, final File dest) throws IOException {
    FileInputStream from = null;
    FileOutputStream to = null;/*  ww  w. java  2s. co  m*/
    try {
        from = new FileInputStream(src);
        to = new FileOutputStream(dest);
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = from.read(buffer)) != -1) {
            to.write(buffer, 0, bytesRead);
        }
    } finally {
        if (from != null) {
            try {
                from.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (to != null) {
            try {
                to.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.arc.embeddedcdt.gui.jtag.ConfigJTAGTab.java

public static void copyFile(File in, File out) {
    try {/*w ww  .  j a  va 2  s. c om*/
        FileInputStream fis = new FileInputStream(in);
        FileOutputStream fos = new FileOutputStream(out);
        try {
            byte[] buf = new byte[1024];
            int i = 0;
            while ((i = fis.read(buf)) != -1) {
                fos.write(buf, 0, i);
            }
        } finally {
            if (fis != null)
                fis.close();
            if (fos != null)
                fos.close();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:FileCopy.java

/**
 * The static method that actually performs the file copy. Before copying the
 * file, however, it performs a lot of tests to make sure everything is as it
 * should be./*from  w ww  . j av  a 2 s .c  om*/
 */
public static void copy(String from_name, String to_name) throws IOException {
    File from_file = new File(from_name); // Get File objects from Strings
    File to_file = new File(to_name);

    // First make sure the source file exists, is a file, and is readable.
    // These tests are also performed by the FileInputStream constructor
    // which throws a FileNotFoundException if they fail.
    if (!from_file.exists())
        abort("no such source file: " + from_name);
    if (!from_file.isFile())
        abort("can't copy directory: " + from_name);
    if (!from_file.canRead())
        abort("source file is unreadable: " + from_name);

    // 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())
            abort("destination file is unwriteable: " + to_name);
        // Ask whether to overwrite it
        System.out.print("Overwrite existing file " + to_file.getName() + "? (Y/N): ");
        System.out.flush();
        // Get the user's response.
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String response = in.readLine();
        // Check the response. If not a Yes, abort the copy.
        if (!response.equals("Y") && !response.equals("y"))
            abort("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(); // The destination directory
        if (parent == null) // If none, use the current directory
            parent = System.getProperty("user.dir");
        File dir = new File(parent); // Convert it to a file.
        if (!dir.exists())
            abort("destination directory doesn't exist: " + parent);
        if (dir.isFile())
            abort("destination is not a directory: " + parent);
        if (!dir.canWrite())
            abort("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]; // To hold file contents
        int bytes_read; // How many bytes in buffer

        // Read a chunk of bytes into the buffer, then write them out,
        // looping until we reach the end of the file (when read() returns
        // -1). Note the combination of assignment and comparison in this
        // while loop. This is a common I/O programming idiom.
        while ((bytes_read = from.read(buffer)) != -1)
            // Read until EOF
            to.write(buffer, 0, bytes_read); // write
    }
    // Always close the streams, even if exceptions were thrown
    finally {
        if (from != null)
            try {
                from.close();
            } catch (IOException e) {
                ;
            }
        if (to != null)
            try {
                to.close();
            } catch (IOException e) {
                ;
            }
    }
}

From source file:com.aurel.track.admin.customize.category.report.ReportBL.java

/**
 * Zips a directory content into a zip stream
 * @param dirZip/*from   w  w  w .  j ava  2 s . c  om*/
 * @param zipOut
 * @param rootPath
 */
public static void zipFiles(File dirZip, ZipOutputStream zipOut, String rootPath) {
    try {
        // get a listing of the directory content
        File[] dirList = dirZip.listFiles();
        byte[] readBuffer = new byte[2156];
        int bytesIn;
        // loop through dirList, and zip the files
        for (int i = 0; i < dirList.length; i++) {
            File f = dirList[i];
            if (f.isDirectory()) {
                // if the File object is a directory, call this
                // function again to add its content recursively
                String filePath = f.getAbsolutePath();
                zipFiles(new File(filePath), zipOut, rootPath);
                // loop again
                continue;
            }
            // if we reached here, the File object f was not a directory
            // create a FileInputStream on top of f
            FileInputStream fis = new FileInputStream(f);
            // create a new zip entry
            ZipEntry anEntry = new ZipEntry(
                    f.getAbsolutePath().substring(rootPath.length() + 1, f.getAbsolutePath().length()));
            // place the zip entry in the ZipOutputStream object
            zipOut.putNextEntry(anEntry);
            // now write the content of the file to the ZipOutputStream
            while ((bytesIn = fis.read(readBuffer)) != -1) {
                zipOut.write(readBuffer, 0, bytesIn);
            }
            // close the Stream
            fis.close();
        }

    } catch (Exception e) {
        LOGGER.error("Zip the " + dirZip.getName() + " failed with " + e.getMessage());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
}

From source file:com.easyhome.common.modules.network.HttpManager.java

private static void imageContentToUpload(OutputStream out, String imgpath) throws WeiboException {
    if (imgpath == null) {
        return;//from  www. j  av  a2  s. co  m
    }
    StringBuilder temp = new StringBuilder();

    temp.append(MP_BOUNDARY).append("\r\n");
    temp.append("Content-Disposition: form-data; name=\"pic\"; filename=\"").append("news_image")
            .append("\"\r\n");
    String filetype = "image/png";
    temp.append("Content-Type: ").append(filetype).append("\r\n\r\n");
    byte[] res = temp.toString().getBytes();
    FileInputStream input = null;
    try {
        out.write(res);
        input = new FileInputStream(imgpath);
        byte[] buffer = new byte[1024 * 50];
        while (true) {
            int count = input.read(buffer);
            if (count == -1) {
                break;
            }
            out.write(buffer, 0, count);
        }
        out.write("\r\n".getBytes());
        out.write(("\r\n" + END_MP_BOUNDARY).getBytes());
    } catch (IOException e) {
        throw new WeiboException(e);
    } finally {
        if (null != input) {
            try {
                input.close();
            } catch (IOException e) {
                throw new WeiboException(e);
            }
        }
    }
}

From source file:com.headswilllol.basiclauncher.Launcher.java

public static String md5(String path) { // convenience method for calculating MD5 hash of a file
    try {//w ww .j  a v  a 2  s  . c om
        MessageDigest md = MessageDigest.getInstance("MD5");
        FileInputStream fis = new FileInputStream(path);
        byte[] dataBytes = new byte[1024];

        int nread;
        while ((nread = fis.read(dataBytes)) != -1) {
            md.update(dataBytes, 0, nread);
        }
        fis.close();

        byte[] mdbytes = md.digest();

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < mdbytes.length; i++) {
            String hex = Integer.toHexString(0xff & mdbytes[i]);
            if (hex.length() == 1)
                sb.append('0');
            sb.append(hex);
        }
        return sb.toString();
    } catch (Exception ex) {
        ex.printStackTrace();
        System.err.println("Failed to calculate checksum for " + path);
        createExceptionLog(ex);
        progress = "Failed to calculate checksum for file!";
        fail = "Errors occurred, see exception log for details";
    }

    return null;
}