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:ch.entwine.weblounge.common.impl.util.TestUtils.java

/**
 * Loads the <code>JSON</code> data from the specified file on the class path
 * and returns it after having stripped off any newlines, line breaks and
 * otherwise disturbing spaces and characters.
 * //from  w  w  w  .ja va 2 s.c o m
 * @param path
 *          the resource path
 * @return the contents of the resource
 */
public static String loadJsonFromResource(String path) {
    File templateFile = new File(TestUtils.class.getResource(path).getPath());
    String template = null;
    try {
        byte[] buffer = new byte[(int) templateFile.length()];
        FileInputStream f = new FileInputStream(templateFile);
        f.read(buffer);
        f.close();
        template = new String(buffer, "utf-8");
        template = template.replaceAll("(\"\\s*)", "\"").replaceAll("(\\s*\")+", "\"");
        template = template.replaceAll("(\\s*\\{\\s*)", "{").replaceAll("(\\s*\\}\\s*)", "}");
        template = template.replaceAll("(\\s*\\[\\s*)", "[").replaceAll("(\\s*\\]\\s*)", "]");
        template = template.replaceAll("(\\s*,\\s*)", ",");
    } catch (IOException e) {
        throw new RuntimeException("Error reading test resource at " + path);
    }
    return template;
}

From source file:com.asual.lesscss.ResourceUtils.java

public static byte[] readBinaryFile(File source) throws IOException {
    byte[] result;
    try {/*  w  w  w  .  ja  va 2 s .c om*/
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        FileInputStream input = new FileInputStream(source);
        try {
            byte[] buffer = new byte[1024];
            int bytesRead = -1;
            while ((bytesRead = input.read(buffer)) != -1) {
                byteStream.write(buffer, 0, bytesRead);
            }
            result = byteStream.toByteArray();
        } finally {
            byteStream.close();
            input.close();
        }
    } catch (IOException e) {
        logger.error("Can't read '" + source.getAbsolutePath() + "'.");
        throw e;
    }
    return result;
}

From source file:Main.java

public static String checkSum(String path) {
    String checksum = null;//from   ww w  .j a va  2 s .  co m
    try {
        FileInputStream fis = new FileInputStream(path);
        MessageDigest md = MessageDigest.getInstance("MD5");

        //Using MessageDigest update() method to provide input
        byte[] buffer = new byte[8192];
        int numOfBytesRead;
        while ((numOfBytesRead = fis.read(buffer)) > 0) {
            md.update(buffer, 0, numOfBytesRead);
        }
        byte[] hash = md.digest();
        checksum = new BigInteger(1, hash).toString(16); //don't use this, truncates leading zero
    } catch (IOException | NoSuchAlgorithmException ignored) {
    }
    assert checksum != null;
    return checksum.trim();
}

From source file:eu.databata.engine.util.PropagationUtils.java

/**
 * This method is suitable for reading files not larger than 2 GB.
 */// w ww.  j  av  a 2 s  .  c  o m
private static String readFile(File file, String encoding) {
    String result = null;
    try {
        FileInputStream inputStream = new FileInputStream(file);
        try {
            byte[] bytes = new byte[(int) inputStream.getChannel().size()];
            inputStream.read(bytes);
            result = Charset.forName(encoding).decode(ByteBuffer.wrap(bytes)).toString();
        } finally {
            inputStream.close();
        }
    } catch (Exception e) {
        LOG.warn("Failed to read file: " + file.getName());
        throw new RuntimeException(e);
    }
    return dos2Unix(result);
}

From source file:com.littcore.io.util.ZipUtils.java

/**
 * ?./*from  ww w.j a v a2 s .c  o m*/
 * 
 * @param out ZIP?
 * @param srcFile ?
 * @param basePath 
 * 
 * @throws IOException Signals that an I/O exception has occurred.
 */
private static void zip(ZipOutputStream out, File srcFile, String basePath) throws IOException {
    if (srcFile.isDirectory()) {
        File[] files = srcFile.listFiles();

        if (files.length == 0) {
            out.putNextEntry(new ZipEntry(basePath + srcFile.getName() + "/")); //?
            out.closeEntry();
        } else {
            basePath += srcFile.getName() + "/";
            for (int i = 0; i < files.length; i++) {
                zip(out, files[i], basePath);
            }
        }

    } else {
        out.putNextEntry(new ZipEntry(basePath + srcFile.getName()));
        FileInputStream in = new FileInputStream(srcFile);
        int len;
        byte[] buf = new byte[BUFFERED_SIZE];
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        out.closeEntry();
        in.close();
    }
}

From source file:Main.java

public static boolean copyFileTo(File srcFile, File destFile) throws IOException {
    if (srcFile == null || destFile == null) {
        return false;
    }/*from  www  .  java  2s. c  o  m*/
    if (srcFile.isDirectory() || destFile.isDirectory())
        return false;
    if (!srcFile.exists()) {
        return false;
    }
    if (!destFile.exists()) {
        createFile(destFile.getAbsolutePath());
    }
    FileInputStream fis = new FileInputStream(srcFile);
    FileOutputStream fos = new FileOutputStream(destFile);
    int readLen = 0;
    byte[] buf = new byte[1024];
    while ((readLen = fis.read(buf)) != -1) {
        fos.write(buf, 0, readLen);
    }
    fos.flush();
    fos.close();
    fis.close();
    return true;
}

From source file:com.twinsoft.convertigo.engine.AttachmentManager.java

static public AttachmentDetails getAttachment(Element eAttachment) {
    try {//  w w w.j  a  va2s  . c  o  m
        if ("attachment".equals(eAttachment.getTagName())
                && "attachment".equals(eAttachment.getAttribute("type"))) {
            String attr;
            final String name = eAttachment.getAttribute("name");
            final String contentType = eAttachment.getAttribute("content-type");
            final byte[][] data = new byte[1][];
            if ((attr = eAttachment.getAttribute("local-url")) != null && attr.length() > 0) {
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(attr);
                    fis.read(data[0] = new byte[fis.available()]);
                } finally {
                    if (fis != null)
                        fis.close();
                }

            } else if ((attr = eAttachment.getAttribute("encoding")) != null && attr.length() > 0) {
                if ("base64".equals(attr)) {
                    data[0] = Base64.decodeBase64(eAttachment.getTextContent());
                }
            }
            if (data[0] != null) {
                return new AttachmentDetails() {
                    public byte[] getData() {
                        return data[0];
                    }

                    public String getName() {
                        return name;
                    }

                    public String getContentType() {
                        return contentType;
                    }
                };
            }
        }
    } catch (Exception e) {
        Engine.logEngine.error("failed to make AttachmentDetails", e);
    }
    return null;
}

From source file:Main.java

public static void copyDirFile(String oldPath, String newPath) {
    try {//from w  w  w  .  jav a  2 s .  c  o  m
        new File(newPath).mkdirs();
        File a = new File(oldPath);
        System.out.println("oldPath:" + 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()) {
                copyDirFile(oldPath + "/" + file[i], newPath + "/" + file[i]);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.sun.portal.os.portlets.PortletChartUtilities.java

private static void writeDefaultImage(OutputStream out, String defaultImagePath) throws IOException {

    FileInputStream fin = null;
    try {//from  w  ww .  j  av a2  s .  c  o m
        byte[] b = new byte[1024];
        fin = new FileInputStream(defaultImagePath);
        while (fin.read(b) != -1) {
            out.write(b);
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        fin.close();
    }
}

From source file:Main.java

/**
 * File to Base64// w ww . j  a  va2 s  . c om
 * @param filePath
 * @return
 * @throws FileNotFoundException
 * @throws IOException
 */
public static String getBase64StringFromFile(String filePath) throws FileNotFoundException, IOException {
    byte[] buffer = null;
    File file = new File(filePath);
    FileInputStream fis = null;
    ByteArrayOutputStream bos = null;
    byte[] b = new byte[1000];
    try {
        fis = new FileInputStream(file);
        bos = new ByteArrayOutputStream(1000);
        int n;
        while ((n = fis.read(b)) != -1) {
            bos.write(b, 0, n);
        }
        fis.close();
        bos.close();
        buffer = bos.toByteArray();
    } catch (FileNotFoundException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } finally {
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    return Base64.encodeToString(buffer, Base64.DEFAULT);
}