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: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;/*from w  w w  .jav  a2  s  .co 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:Main.java

/**
 * read file to a string//from w ww  .  j  a va 2s .  co  m
 * 
 * @param context
 * @param file
 * @return
 */
public static String loadString(File file) {
    if (null == file || !file.exists()) {
        return "";
    }
    FileInputStream fis = null;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        fis = new FileInputStream(file);
        int restSize = fis.available();
        int bufSize = restSize > BUF_SIZE ? BUF_SIZE : restSize;
        byte[] buf = new byte[bufSize];
        while (fis.read(buf) != -1) {
            baos.write(buf);
            restSize -= bufSize;

            if (restSize <= 0)
                break;
            if (restSize < bufSize)
                bufSize = restSize;
            buf = new byte[bufSize];
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return baos.toString();
}

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

/**
 *
 *
 * @param keyfile//  www  .ja  va 2  s  .  c o m
 *
 * @return
 *
 * @throws InvalidSshKeyException
 * @throws IOException
 */
public static SshPublicKeyFile parse(File keyfile) throws InvalidSshKeyException, IOException {
    FileInputStream in = new FileInputStream(keyfile);
    byte[] data = new byte[in.available()];
    in.read(data);
    in.close();

    return parse(data);
}

From source file:cc.arduino.utils.FileHash.java

/**
 * Calculate a message digest of a file using the algorithm specified. The
 * result is a string containing the algorithm name followed by ":" and by the
 * resulting hash in hex.//from  w  w w .  jav a  2 s .com
 *
 * @param file
 * @param algorithm For example "SHA-256"
 * @return The algorithm followed by ":" and the hash, for example:<br />
 * "SHA-256:ee6796513086080cca078cbb383f543c5e508b647a71c9d6f39b7bca41071883"
 * @throws IOException
 * @throws NoSuchAlgorithmException
 */
public static String hash(File file, String algorithm) throws IOException, NoSuchAlgorithmException {
    FileInputStream in = null;
    try {
        in = new FileInputStream(file);
        byte buff[] = new byte[10240];
        MessageDigest digest = MessageDigest.getInstance(algorithm);
        while (in.available() > 0) {
            int read = in.read(buff);
            digest.update(buff, 0, read);
        }
        byte[] hash = digest.digest();
        String res = "";
        for (byte b : hash) {
            int c = b & 0xFF;
            if (c < 0x10)
                res += "0";
            res += Integer.toHexString(c);
        }
        return algorithm + ":" + res;
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:org.kimios.kernel.repositories.RepositoryManager.java

public static void writeVersion(DocumentVersion version, InputStream in)
        throws DataSourceException, ConfigException, RepositoryException {
    try {/*from   w  w  w.ja  va2 s .  co m*/
        String storageDirPath = version.getStoragePath().substring(0,
                version.getStoragePath().lastIndexOf("/"));
        File f = new File(manager.defaultRepositoryPath + storageDirPath);
        if (!f.exists()) {
            boolean created = f.mkdirs();
        }
        BufferedOutputStream out = new BufferedOutputStream(
                new FileOutputStream(manager.defaultRepositoryPath + version.getStoragePath()));
        BufferedInputStream input = new BufferedInputStream(in);
        int len = 0;
        byte[] buffer = new byte[10000];
        while ((len = input.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        out.flush();
        out.close();

        FileInputStream fis = new FileInputStream(manager.defaultRepositoryPath + version.getStoragePath());
        version.setLength(fis.available());
        fis.close();
    } catch (IOException e) {
        throw new RepositoryException(e.getMessage());
    }
}

From source file:com.ca.dvs.app.dvs_servlet.misc.FileUtil.java

/**
 * A quick test to determine if uploaded file is a ZIP file
 * <p> // ww w  . j  a  v  a  2s. c om
 * @param file the file to interrogate for being a zip file 
 * @return true is the specified file is a zip file
 * @throws IOException
 */
public static boolean isZipFile(File file) throws IOException {

    boolean isZipFile = false;
    FileInputStream fileInputStream = null;

    try {

        fileInputStream = new FileInputStream(file);

        if (fileInputStream.available() > ZIP_SIGNATURE.length) {

            byte[] magic = new byte[ZIP_SIGNATURE.length];

            if (ZIP_SIGNATURE.length == fileInputStream.read(magic, 0, ZIP_SIGNATURE.length)) {

                isZipFile = Arrays.equals(magic, ZIP_SIGNATURE);

            }

        }

    } finally {

        if (null != fileInputStream) {
            fileInputStream.close();
        }

    }

    return isZipFile;
}

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;//from ww w. j  ava 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:com.github.commonclasses.network.DownloadUtils.java

public static long download(String urlStr, File dest, boolean append, DownloadListener downloadListener)
        throws Exception {
    int downloadProgress = 0;
    long remoteSize = 0;
    int currentSize = 0;
    long totalSize = -1;

    if (!append && dest.exists() && dest.isFile()) {
        dest.delete();//from  w  w  w  .jav  a 2 s .  co  m
    }

    if (append && dest.exists() && dest.exists()) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(dest);
            currentSize = fis.available();
        } catch (IOException e) {
            throw e;
        } finally {
            if (fis != null) {
                fis.close();
            }
        }
    }

    HttpGet request = new HttpGet(urlStr);
    request.setHeader("Content-Type", "application/x-www-form-urlencoded");

    if (currentSize > 0) {
        request.addHeader("RANGE", "bytes=" + currentSize + "-");
    }

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, CONNECT_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, DATA_TIMEOUT);
    HttpClient httpClient = new DefaultHttpClient(params);

    InputStream is = null;
    FileOutputStream os = null;
    try {
        HttpResponse response = httpClient.execute(request);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            is = response.getEntity().getContent();
            remoteSize = response.getEntity().getContentLength();
            Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                is = new GZIPInputStream(is);
            }
            os = new FileOutputStream(dest, append);
            byte buffer[] = new byte[DATA_BUFFER];
            int readSize = 0;
            while ((readSize = is.read(buffer)) > 0) {
                os.write(buffer, 0, readSize);
                os.flush();
                totalSize += readSize;
                if (downloadListener != null) {
                    downloadProgress = (int) (totalSize * 100 / remoteSize);
                    downloadListener.downloading(downloadProgress);
                }
            }
            if (totalSize < 0) {
                totalSize = 0;
            }
        }
    } catch (Exception e) {
        if (downloadListener != null) {
            downloadListener.exception(e);
        }
        e.printStackTrace();
    } finally {
        if (os != null) {
            os.close();
        }
        if (is != null) {
            is.close();
        }
    }

    if (totalSize < 0) {
        throw new Exception("Download file fail: " + urlStr);
    }

    if (downloadListener != null) {
        downloadListener.downloaded(dest);
    }

    return totalSize;
}

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

/**
 *
 *
 * @param keyfile//from  w  ww  . java2  s . c  o  m
 *
 * @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.twinsoft.convertigo.engine.AttachmentManager.java

static public AttachmentDetails getAttachment(Element eAttachment) {
    try {//from   www  . j a  va 2 s  . 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;
}