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

public static void copyFolder(String oldPath, String newPath) {

    try {/*w  w  w. j a va 2 s.  co  m*/
        (new File(newPath)).mkdirs();
        File a = new File(oldPath);
        String[] file = a.list();
        File temp = null;
        for (int i = 0; i < file.length; i++) {
            if (oldPath.endsWith(File.separator)) {
                temp = new File(oldPath + file[i]);
            } else {
                temp = new File(oldPath + File.separator + file[i]);
            }

            if (temp.isFile()) {
                FileInputStream input = new FileInputStream(temp);
                FileOutputStream output = new FileOutputStream(newPath + "/" + (temp.getName()).toString());
                byte[] b = new byte[1024 * 5];
                int len;
                while ((len = input.read(b)) != -1) {
                    output.write(b, 0, len);
                }
                output.flush();
                output.close();
                input.close();
            }
            if (temp.isDirectory()) {
                copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "copyFolder() copy dir error", e);
    }

}

From source file:com.bmw.spdxeditor.editors.spdx.SPDXEditorUtility.java

/**
 * Calculate the SHA1 value for the file given in path
 * @param path/*w  w w  . j a  va  2s.  co m*/
 * @return
 * @throws Exception
 */
public static String calculateSHA1(File path) throws Exception {
    MessageDigest md = MessageDigest.getInstance("SHA1");
    FileInputStream fis = new FileInputStream(path);
    byte[] dataBytes = new byte[1024];

    int nread = 0;

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

    byte[] mdbytes = md.digest();

    //convert the byte to hex format
    StringBuffer sb = new StringBuffer("");
    for (int i = 0; i < mdbytes.length; i++) {
        sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
    }

    return sb.toString();
}

From source file:Main.java

public static void modifyByte(Activity activity, File srcFile, String destFile, byte[] byteNums,
        byte[] byteContents) {
    //        throw new UnsupportedOperationException("Not yet implemented");
    //        UIUtils.log("Modifying byte: " + byteNum + " in sdcard file: " + srcFile);
    try {//from  w w  w  .j a  v a  2s  .  co m
        FileInputStream is = new FileInputStream(srcFile); // open the input stream for reading
        OutputStream os = new FileOutputStream(destFile);
        byte[] buf = new byte[8092];
        int n;
        int totalBytes = 0;
        while ((n = is.read(buf)) > 0) {
            totalBytes += n;
            //                UIUtils.log("Total Bytes read: " + totalBytes);
            for (int i = 0; i < byteNums.length; i++) {
                if (byteNums[i] <= totalBytes) {
                    //                    UIUtils.log("Replacing byte: " + (totalBytes - n + byteNum ) + " contents with: " + byteContents);
                    buf[totalBytes - n + byteNums[i]] = byteContents[i];
                }
            }
            os.write(buf, 0, n);
        }
        //            UIUtils.log(ByteUtils.ByteArrayToString(buf));
        os.close();
        is.close();
    } catch (Exception ex) {
        Log.e("Installer", "failed to modify file: " + ex);
    }
}

From source file:com.zving.platform.SysInfo.java

public static void downloadDB(HttpServletRequest request, HttpServletResponse response) {
    try {//from   w  w w  . j a  va  2 s  .  co  m
        request.setCharacterEncoding(Constant.GlobalCharset);
        response.reset();
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition",
                "attachment; filename=DB_" + DateUtil.getCurrentDate("yyyyMMddHHmmss") + ".dat");
        OutputStream os = response.getOutputStream();

        String path = Config.getContextRealPath() + "WEB-INF/data/backup/DB_"
                + DateUtil.getCurrentDate("yyyyMMddHHmmss") + ".dat";
        new DBExport().exportDB(path);

        byte[] buffer = new byte[1024];
        int read = -1;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(path);
            while ((read = fis.read(buffer)) != -1)
                if (read > 0) {
                    byte[] chunk = (byte[]) null;
                    if (read == 1024) {
                        chunk = buffer;
                    } else {
                        chunk = new byte[read];
                        System.arraycopy(buffer, 0, chunk, 0, read);
                    }
                    os.write(chunk);
                    os.flush();
                }
        } finally {
            if (fis != null) {
                fis.close();
            }
        }
        os.flush();
        os.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.glaf.core.security.DigestUtil.java

public static void digestFile(String filename, String algorithm) {
    byte[] b = new byte[65536];
    int read = 0;
    FileInputStream fis = null;
    FileOutputStream fos = null;// w w w.ja va 2 s  .  c  o m
    OutputStream encodedStream = null;
    try {
        MessageDigest md = MessageDigest.getInstance(algorithm);
        fis = new FileInputStream(filename);
        while (fis.available() > 0) {
            read = fis.read(b);
            md.update(b, 0, read);
        }
        byte[] digest = md.digest();
        StringBuffer fileNameBuffer = new StringBuffer(256).append(filename).append('.').append(algorithm);
        fos = new FileOutputStream(fileNameBuffer.toString());
        encodedStream = MimeUtility.encode(fos, "base64");
        encodedStream.write(digest);
        fos.flush();
    } catch (Exception ex) {
        throw new RuntimeException("Error computing Digest: " + ex);
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(encodedStream);
    }
}

From source file:MainWindowLogic.java

static void isTextFile(File fil_hnd) throws IncorrectFileTypeException, FileNotFoundException, IOException {
    FileInputStream in = new FileInputStream(fil_hnd);
    int size = in.available();
    if (size > 1000)
        size = 1000;//ww w  .  j  a v a2s  .  c  o m
    byte[] data = new byte[size];
    in.read(data);
    in.close();
    String s = new String(data, "ISO-8859-1");
    String s2 = s.replaceAll("[a-zA-Z0-9\\.\\*!\"\\$\\%&/()=\\?@~'#:,;\\"
            + "+><\\|\\[\\]\\{\\}\\^\\\\ \\n\\r\\t_\\-`"
            + "??]", "");
    // will delete all text signs

    double d = (double) (s.length() - s2.length()) / (double) (s.length());
    // percentage of text signs in the text
    if (!(d > 0.950))
        throw new IncorrectFileTypeException();

}

From source file:controllers.user.UserAvatarApp.java

@Deprecated
public static Result render(File file) {
    try {//  w  ww .j  a v  a2  s .  c  om
        FileInputStream in = new FileInputStream(file);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] b = new byte[2048];
        int len = -1;
        while ((len = in.read(b)) != -1) {
            out.write(b, 0, len);
        }
        in.close();
        return ok(out.toByteArray());
    } catch (Exception e) {
        Logger.error("render user avatar error ", e);
    }
    return ok();
}

From source file:controlador.Red.java

/**
 * Envio de un fichero desde el Cliente Local al Server FTP.
 * @param rutaLocal Ruta del Cliente donde se buscara el fichero.
 * @param name Nombre con el cual se buscara y creara el fichero.
 * @return Estado de la operacion.//w w w  .  ja v a2s  .c  om
 */
public static boolean sendFile(String rutaLocal, String name) {
    try {
        url = new URL(conexion + name);
        URLConnection urlConn = url.openConnection();
        OutputStream os = urlConn.getOutputStream();
        FileInputStream fis = new FileInputStream(new File(rutaLocal + name));
        byte[] buffer = new byte[BUFFER_LENGTH];

        int count;
        while ((count = fis.read(buffer)) > 0) {
            os.write(buffer, 0, count);
        }
        os.flush();
        os.close();
        fis.close();

        return true;
    } catch (IOException ex) {
        ex.printStackTrace();
        System.out.println("Problema al enviar un fichero al server: " + ex.getLocalizedMessage());
    }

    return false;
}

From source file:Main.java

public static boolean copyFile(File from, File to, byte[] buf) {
    if (buf == null)
        buf = new byte[BUFFER_SIZE];

    ///*ww w  . j  a  va  2s. co m*/
    // System.out.println("Copy file ("+from+","+to+")");
    FileInputStream from_s = null;
    FileOutputStream to_s = null;

    try {
        from_s = new FileInputStream(from);
        to_s = new FileOutputStream(to);

        for (int bytesRead = from_s.read(buf); bytesRead != -1; bytesRead = from_s.read(buf))
            to_s.write(buf, 0, bytesRead);

        from_s.close();
        from_s = null;

        to_s.getFD().sync(); // RESOLVE: sync or no sync?
        to_s.close();
        to_s = null;
    } catch (IOException ioe) {
        return false;
    } finally {
        if (from_s != null) {
            try {
                from_s.close();
            } catch (IOException ioe) {
            }
        }
        if (to_s != null) {
            try {
                to_s.close();
            } catch (IOException ioe) {
            }
        }
    }

    return true;
}

From source file:Main.java

public static byte[] readFile(File file) throws IOException {
    if (!file.exists()) {
        throw new IOException("not crete file=" + file.getAbsolutePath());
    }//from w  ww . j  av  a2  s  . c om
    FileInputStream fileInputStream = null;
    ByteArrayOutputStream byteArrayOutputStream = null;
    try {
        fileInputStream = new FileInputStream(file);
        byteArrayOutputStream = new ByteArrayOutputStream(64);
        int length = 0;
        byte[] buffer = new byte[1024];
        while ((length = fileInputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, length);
        }
        return byteArrayOutputStream.toByteArray();
    } finally {
        if (fileInputStream != null) {
            fileInputStream.close();
        }
        if (byteArrayOutputStream != null) {
            byteArrayOutputStream.close();
        }
    }
}