Example usage for java.io FileInputStream available

List of usage examples for java.io FileInputStream available

Introduction

In this page you can find the example usage for java.io FileInputStream available.

Prototype

public int available() throws IOException 

Source Link

Document

Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

Usage

From source file:yui.classes.utils.IOUtils.java

public static String readFileContent(String path) {
    try {/*from   w  w  w  .  j  a  v  a2  s .c o m*/
        if (!new File(path).exists()) {
            return "";
        }

        FileInputStream fis = new FileInputStream(path);
        int x = fis.available();
        byte[] b = new byte[x];

        fis.read(b);

        return new String(b);
    } catch (IOException e) {
        // Ignore
    }

    return "";
}

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  w  ww .  ja v a2s. 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;
}

From source file:gov.nasa.arc.geocam.geocam.HttpPost.java

protected static void assembleMultipartFiles(DataOutputStream out, Map<String, String> vars,
        Map<String, File> files) throws IOException {
    for (String key : vars.keySet()) {
        out.writeBytes("--" + BOUNDARY + CRLF);
        out.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + CRLF);
        out.writeBytes(CRLF);//from   w ww .j ava2  s .c  o m
        out.writeBytes(vars.get(key) + CRLF);
    }

    for (String key : files.keySet()) {
        File f = files.get(key);
        out.writeBytes("--" + BOUNDARY + CRLF);
        out.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"; filename=\"" + f.getName() + "\""
                + CRLF);
        out.writeBytes("Content-Type: application/octet-stream" + CRLF);
        out.writeBytes(CRLF);

        // write file
        int maxBufferSize = 1024;
        FileInputStream fin = new FileInputStream(f);
        int bytesAvailable = fin.available();
        int bufferSize = Math.min(maxBufferSize, bytesAvailable);
        byte[] buffer = new byte[bufferSize];

        int bytesRead = fin.read(buffer, 0, bufferSize);
        while (bytesRead > 0) {
            out.write(buffer, 0, bufferSize);
            bytesAvailable = fin.available();
            bufferSize = Math.min(maxBufferSize, bytesAvailable);
            bytesRead = fin.read(buffer, 0, bufferSize);
        }
    }
    out.writeBytes(CRLF);
    out.writeBytes("--" + BOUNDARY + "--" + CRLF);
    out.writeBytes(CRLF);
}

From source file:org.panlab.tgw.restclient.PtmInfoParser.java

private static void storeNewPTM(String alias, URL url, String dn) {
    try {//w ww  . j a  va 2 s .  co m

        File file = new File("conf.xml");
        String content;
        if (file.exists()) {
            FileInputStream fis = new FileInputStream(file);
            int length = fis.available();
            byte bArray[] = new byte[length];
            fis.read(bArray);
            fis.close();
            content = new String(bArray);
        } else
            content = "<ptms></ptms>";

        Object objs[] = XMLUtil.getElements(content);
        FileOutputStream fos = new FileOutputStream("conf.xml");

        fos.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".getBytes());
        fos.write("<ptms>\n".getBytes());

        if (objs != null) {
            for (int i = 0; i < objs.length; i++) {
                XMLElement element = (XMLElement) (objs[i]);
                fos.write((element.toString() + "\n").getBytes());
            }
        }
        XMLElement elem = new XMLElement(alias, "cert", "\"" + dn + "\"", url.toString());
        fos.write((elem.toString() + "\n").getBytes());
        fos.write("</ptms>\n".getBytes());
        fos.close();

    } catch (Exception error) {
        log.error(error.getMessage());
    }
}

From source file:Main.java

/**
 * This method handels the reading of data from a specific file.
 * //from w  w  w  .  j ava 2  s.  co m
 * @param file the file, to read from.
 * @param blockSize the length of the data-block, which should be read from the specified file.
 * @return the data read from the file.
 */
public static byte[] readFile(File file, long blockSize) {
    FileInputStream fis;
    byte[] fileContent = null;

    try {
        fis = new FileInputStream(file);

        FileChannel fileChannel = fis.getChannel();

        int bytesToRead;
        fileChannel.position(readStreamPosition);

        int dataLen = fis.available();

        // if there is a zero block size specified, read the whole file
        if (blockSize == 0L) {
            bytesToRead = dataLen;
        } else {
            bytesToRead = (int) blockSize;
        }

        fileContent = new byte[bytesToRead];

        // reading the data
        for (int i = 0; i < bytesToRead; i++) {
            fileContent[i] = (byte) fis.read();
        }

        // storing read-position
        readStreamPosition = fileChannel.position();

        fis.close();
        fileChannel.close();

        // zero blockSize indicates, that reading of this file is completed,
        // stream position reset
        if (blockSize == 0L) {
            readStreamPosition = 0L;
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return fileContent;
}

From source file:org.tinymediamanager.core.License.java

public static Properties decrypt() {
    try {/*from w  w w . ja v a2 s  . com*/
        FileInputStream input = new FileInputStream(getLicenseFile());
        byte[] fileData = new byte[input.available()];
        input.read(fileData);
        input.close();
        String lic = new String(fileData, "UTF-8");

        String iv = "F27D5C9927726BCEFE7510B1BDD3D137";
        String salt = "3FF2EC019C627B945225DEBAD71A01B6985FE84C95A70EB132882F88C0A59A55";
        AesUtil util = new AesUtil(128, 100);

        Properties prop = new Properties();
        try {
            // try to decrypt with new/correct MAC implementation
            String decrypt = util.decrypt(salt, iv, getMac(), lic);
            StringReader reader = new StringReader(decrypt);
            prop.load(reader);
        } catch (Exception e) {
            // didn't work? try it with all our found MACs (+ an empty one of an old impl)
            for (String mac : getAllMacAddresses()) {
                try {
                    String decrypt = util.decrypt(salt, iv, mac, lic);
                    StringReader reader = new StringReader(decrypt);
                    prop.load(reader);
                } catch (Exception e2) {
                }
            }
        }
        return prop.size() > 0 ? prop : null; // return NULL when properties are empty
    } catch (Exception e) {
        // file not found or whatever
        LOGGER.error("Error decrypting license file", e);
        return null;
    }
}

From source file:com.sinpo.xnfc.nfc.Util.java

public static String readFileSdcardFile(String fileName) throws IOException {
    String res = "";
    try {//from   www. java 2  s .  c  o  m
        FileInputStream fin = new FileInputStream(fileName);

        int length = fin.available();

        byte[] buffer = new byte[length];
        fin.read(buffer);

        res = EncodingUtils.getString(buffer, "UTF-8");

        fin.close();
    }

    catch (Exception e) {
        e.printStackTrace();
    }
    return res;
}

From source file:org.sakaiproject.linktool.LinkToolUtil.java

private static SecretKey readSecretKey(String filename, String alg) {
    FileInputStream file = null;
    SecretKey privkey = null;/*from ww w.j  a v  a  2  s.co m*/
    try {
        file = new FileInputStream(filename);
        byte[] bytes = new byte[file.available()];
        file.read(bytes);
        privkey = new SecretKeySpec(bytes, alg);
    } catch (Exception e) {
        M_log.error("Unable to read key from " + filename);
        privkey = null;
    } finally {
        if (file != null) {
            try {
                file.close();
            } catch (Exception e) {
                M_log.error("Unable to close file " + filename);
            }
        }
    }
    return privkey;
}

From source file:one.nio.serial.Repository.java

public static int loadSnapshot(String fileName) throws IOException, ClassNotFoundException {
    FileInputStream fis = new FileInputStream(fileName);
    try {//from   ww  w .j  a  v a 2  s .co  m
        byte[] snapshot = new byte[fis.available()];
        fis.read(snapshot);
        return loadSnapshot(snapshot);
    } finally {
        fis.close();
    }
}

From source file:com.intuit.s3encrypt.S3Encrypt.java

public static KeyPair loadKeyPair(String filename, String algorithm)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    // Read public key from file.
    FileInputStream keyfis = new FileInputStream(filename + ".pub");
    byte[] encodedPublicKey = new byte[keyfis.available()];
    keyfis.read(encodedPublicKey);//w  w  w  .j  av a2 s.  c  o  m
    keyfis.close();

    // Read private key from file.
    keyfis = new FileInputStream(filename);
    byte[] encodedPrivateKey = new byte[keyfis.available()];
    keyfis.read(encodedPrivateKey);
    keyfis.close();

    // Generate KeyPair from public and private keys.
    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    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);

}