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:game.com.HandleDownloadFolderServlet.java

public static void addDirToZipArchive(ZipOutputStream zos, File fileToZip, String parrentDirectoryName)
        throws Exception {
    if (fileToZip == null || !fileToZip.exists()) {
        return;//from w w w  .j a v a  2 s  .  c  o  m
    }

    String zipEntryName = fileToZip.getName();
    if (parrentDirectoryName != null && !parrentDirectoryName.isEmpty()) {
        zipEntryName = parrentDirectoryName + "/" + fileToZip.getName();
    }

    if (fileToZip.isDirectory()) {
        System.out.println("+" + zipEntryName);
        for (File file : fileToZip.listFiles()) {
            addDirToZipArchive(zos, file, zipEntryName);
        }
    } else {
        System.out.println("   " + zipEntryName);
        byte[] buffer = new byte[1024];
        FileInputStream fis = new FileInputStream(fileToZip);
        zos.putNextEntry(new ZipEntry(zipEntryName));
        int length;
        while ((length = fis.read(buffer)) > 0) {
            zos.write(buffer, 0, length);
        }
        zos.closeEntry();
        fis.close();
    }
}

From source file:Main.java

private static byte[] MD5EncodeFileByte(File filename) {
    if (filename != null) {
        int i;/*from  ww  w . ja va 2  s.  c  o  m*/
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
        byte[] data = new byte[4096];
        FileInputStream fis;
        try {
            fis = new FileInputStream(filename);
        } catch (FileNotFoundException e2) {
            e2.printStackTrace();
            return null;
        }
        while (true) {
            try {
                i = fis.read(data);
                if (i != -1) {
                    md.update(data, 0, i);
                } else {
                    fis.close();
                    return md.digest();
                }
            } catch (IOException e) {
                e.printStackTrace();
                try {
                    fis.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                return null;
            }
        }
    }
    return null;
}

From source file:org.openmrs.module.omodexport.util.OmodExportUtil.java

/**
 * Utility method for zipping a list of files
 * /*from w  w w . ja  v a 2 s  .  c o  m*/
 * @param files -The list of files to zip
 * @param out
 * @throws FileNotFoundException
 * @throws IOException
 */
public static void zipFiles(List<File> files, ZipOutputStream out) throws FileNotFoundException, IOException {
    byte[] buffer = new byte[4096]; // Create a buffer for copying
    int bytesRead;

    for (File f : files) {
        if (f.isDirectory())
            continue;// Ignore directory
        FileInputStream in = new FileInputStream(f); // Stream to read file
        out.putNextEntry(new ZipEntry(f.getName())); // Store entry
        while ((bytesRead = in.read(buffer)) != -1)
            out.write(buffer, 0, bytesRead);
        in.close();
    }

    out.close();
}

From source file:com.sshtools.j2ssh.transport.publickey.SshPrivateKeyFile.java

/**
 *
 *
 * @param keyfile/*from w  w w. j ava2 s. c  om*/
 *
 * @return
 *
 * @throws InvalidSshKeyException
 * @throws IOException
 */
public static SshPrivateKeyFile parse(File keyfile) throws InvalidSshKeyException, IOException {
    FileInputStream in = new FileInputStream(keyfile);
    byte[] data = null;

    try {
        data = new byte[in.available()];
        in.read(data);
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
        }
    }

    return parse(data);
}

From source file:com.zimbra.cs.service.util.ItemDataFile.java

static void addFile(File f, String topdir, Set<MailItem.Type> types, TarOutputStream tos) throws IOException {
    ItemData id = null;/* w w w.j  ava2  s . c  o  m*/
    String path = f.getPath();
    File mf = new File(path + ".meta");
    TarEntry te;
    MailItem.Type type;

    if (path.indexOf(topdir) == 0)
        path = path.substring(topdir.length() + 1);
    path = path.replace('\\', '/');
    if (mf.exists()) {
        byte[] meta = new byte[(int) mf.length()];
        FileInputStream fis = new FileInputStream(mf);

        if (fis.read(meta) != mf.length()) {
            throw new IOException("meta read err: " + f.getPath());
        }
        fis.close();
        id = new ItemData(meta);
        type = MailItem.Type.of(id.ud.type);
        if (skip(types, type)) {
            return;
        }
        te = new TarEntry(path + ".meta");
        System.out.println(te.getName());
        te.setGroupName(MailItem.Type.of(id.ud.type).toString());
        te.setMajorDeviceId(id.ud.type);
        te.setModTime(mf.lastModified());
        te.setSize(meta.length);
        tos.putNextEntry(te);
        tos.write(meta);
        tos.closeEntry();
    } else {
        if (path.endsWith(".csv") || path.endsWith(".vcf")) {
            type = MailItem.Type.CONTACT;
        } else if (path.endsWith(".eml")) {
            type = MailItem.Type.MESSAGE;
        } else if (path.endsWith(".ics")) {
            if (path.startsWith("Tasks/")) {
                type = MailItem.Type.TASK;
            } else {
                type = MailItem.Type.APPOINTMENT;
            }
        } else if (path.endsWith(".wiki")) {
            type = MailItem.Type.WIKI;
        } else {
            type = MailItem.Type.DOCUMENT;
        }
        if (skip(types, type)) {

        }
        return;
    }
    if (f.exists() && !f.isDirectory() && (id != null || types == null)) {
        byte[] buf = new byte[TarBuffer.DEFAULT_BLKSIZE];
        FileInputStream fis = new FileInputStream(f);
        int in;

        te = new TarEntry(path);
        System.out.println(te.getName());
        te.setGroupName(MailItem.Type.of(id.ud.type).toString());
        te.setMajorDeviceId(id.ud.type);
        te.setModTime(mf.lastModified());
        te.setSize(f.length());
        tos.putNextEntry(te);
        while ((in = fis.read(buf)) > 0)
            tos.write(buf, 0, in);
        fis.close();
        tos.closeEntry();
    }
}

From source file:Main.java

public static void copy(String source, String target, boolean isFolder) throws Exception {
    if (isFolder) {
        (new File(target)).mkdirs();
        File a = new File(source);
        String[] file = a.list();
        File temp = null;//from  www . ja va2  s.  c om
        for (int i = 0; i < file.length; i++) {
            if (source.endsWith(File.separator)) {
                temp = new File(source + file[i]);
            } else {
                temp = new File(source + File.separator + file[i]);
            }
            if (temp.isFile()) {
                FileInputStream input = new FileInputStream(temp);
                FileOutputStream output = new FileOutputStream(target + "/" + (temp.getName()).toString());
                byte[] b = new byte[1024];
                int len;
                while ((len = input.read(b)) != -1) {
                    output.write(b, 0, len);
                }
                output.flush();
                output.close();
                input.close();
            }
            if (temp.isDirectory()) {
                copy(source + "/" + file[i], target + "/" + file[i], true);
            }
        }
    } else {
        int byteread = 0;
        File oldfile = new File(source);
        if (oldfile.exists()) {
            InputStream inStream = new FileInputStream(source);
            File file = new File(target);
            file.getParentFile().mkdirs();
            file.createNewFile();
            FileOutputStream fs = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            while ((byteread = inStream.read(buffer)) != -1) {
                fs.write(buffer, 0, byteread);
            }
            inStream.close();
            fs.close();
        }
    }
}

From source file:Main.java

private static void zipDir(String dir, ZipOutputStream out) throws IOException {
    File directory = new File(dir);

    URI base = directory.toURI();

    ArrayList<File> filesToZip = new ArrayList<File>();

    GetFiles(directory, filesToZip);//w w  w . ja va  2  s .c o  m

    for (int i = 0; i < filesToZip.size(); ++i) {
        FileInputStream in = new FileInputStream(filesToZip.get(i));

        String name = base.relativize(filesToZip.get(i).toURI()).getPath();

        out.putNextEntry(new ZipEntry(name));

        byte[] buf = new byte[4096];
        int bytes = 0;

        while ((bytes = in.read(buf)) != -1) {
            out.write(buf, 0, bytes);
        }

        out.closeEntry();

        in.close();
    }

    out.finish();
    out.flush();
}

From source file:com.vexsoftware.votifier.util.rsa.RSAIO.java

/**
 * Loads an RSA key pair from a directory. The directory must have the files
 * "public.key" and "private.key"./*from  w  ww . java2  s.c o  m*/
 * 
 * @param directory
 *            The directory to load from
 * @return The key pair
 * @throws Exception
 *             If an error occurs
 */
public static KeyPair load(File directory) throws Exception {
    // Read the public key file.
    File publicKeyFile = new File(directory + "/public.key");
    FileInputStream in = null;
    byte[] encodedPublicKey;
    try {
        in = new FileInputStream(directory + "/public.key");
        encodedPublicKey = new byte[(int) publicKeyFile.length()];
        in.read(encodedPublicKey);
        encodedPublicKey = DatatypeConverter.parseBase64Binary(new String(encodedPublicKey));
    } finally {
        try {
            in.close();
        } catch (Exception exception) {
            // ignore
        }
    }

    // Read the private key file.
    File privateKeyFile = new File(directory + "/private.key");
    byte[] encodedPrivateKey;
    try {
        in = new FileInputStream(directory + "/private.key");
        encodedPrivateKey = new byte[(int) privateKeyFile.length()];
        in.read(encodedPrivateKey);
        encodedPrivateKey = DatatypeConverter.parseBase64Binary(new String(encodedPrivateKey));
    } finally {
        try {
            in.close();
        } catch (Exception exception) {
            // ignore
        }
    }

    // Instantiate and return the key pair.
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
    return new KeyPair(publicKey, privateKey);
}

From source file:com.attilax.zip.FileUtil.java

/**
 * //w  w w. j  a  v  a2 s. co  m
 * 
 * @param source     ?
 * @param target         
 * @param cache        ?
 * @throws Exception
 */
public static void mv(String source, String target, int cache) throws Exception {
    if (source.trim().equals(target.trim()))
        return;
    byte[] cached = new byte[cache];
    FileInputStream fromFile = new FileInputStream(source);
    FileOutputStream toFile = new FileOutputStream(target);
    while (fromFile.read(cached) != -1) {
        toFile.write(cached);
    }
    toFile.flush();
    toFile.close();
    fromFile.close();
    new File(source).deleteOnExit();
}

From source file:edu.cornell.mannlib.vitro.webapp.auth.identifier.common.IsBlacklisted.java

/**
 * Runs the SPARQL query in the file with the uri of the individual
 * substituted in.//from www .  ja  v a  2s.c  o  m
 * 
 * The URI of ind will be substituted into the query where ever the token
 * "?individualURI" is found.
 * 
 * If there are any solution sets, then the URI of the variable named
 * "cause" will be returned. Make sure that it is a resource with a URI.
 * Otherwise null will be returned.
 */
private static String runSparqlFileForBlacklist(File file, Individual ind, ServletContext context) {
    if (!file.canRead()) {
        log.debug("cannot read blacklisting SPARQL file " + file.getName());
        return NOT_BLACKLISTED;
    }

    String queryString = null;
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(file);
        byte b[] = new byte[fis.available()];
        fis.read(b);
        queryString = new String(b);
    } catch (IOException ioe) {
        log.debug(ioe);
        return NOT_BLACKLISTED;
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                log.warn("could not close file", e);
            }
        }
    }

    if (StringUtils.isEmpty(queryString)) {
        log.debug(file.getName() + " is empty");
        return NOT_BLACKLISTED;
    }

    OntModel model = ModelAccess.on(context).getOntModel();

    queryString = queryString.replaceAll("\\?individualURI", "<" + ind.getURI() + ">");
    log.debug(queryString);

    Query query = QueryFactory.create(queryString);
    QueryExecution qexec = QueryExecutionFactory.create(query, model);
    try {
        ResultSet results = qexec.execSelect();
        while (results.hasNext()) {
            QuerySolution solution = results.nextSolution();
            if (solution.contains("cause")) {
                RDFNode node = solution.get("cause");
                if (node.isResource()) {
                    return node.asResource().getURI();
                } else if (node.isLiteral()) {
                    return node.asLiteral().getString();
                }
            } else {
                log.error("Query solution must contain a variable " + "\"cause\" of type Resource or Literal.");
                return NOT_BLACKLISTED;
            }
        }
    } finally {
        qexec.close();
    }
    return NOT_BLACKLISTED;
}