Example usage for java.io File length

List of usage examples for java.io File length

Introduction

In this page you can find the example usage for java.io File length.

Prototype

public long length() 

Source Link

Document

Returns the length of the file denoted by this abstract pathname.

Usage

From source file:com.iyonger.apm.web.util.FileDownloadUtils.java

/**
 * Download the given file to the given {@link HttpServletResponse}.
 *
 * @param response {@link HttpServletResponse}
 * @param file     file path//from   w  w w . j  a  v a 2  s.  c om
 * @return true if succeeded
 */
public static boolean downloadFile(HttpServletResponse response, File file) {
    if (file == null || !file.exists()) {
        return false;
    }
    boolean result = true;
    response.reset();
    response.addHeader("Content-Disposition", "attachment;filename=" + file.getName());
    response.setContentType("application/octet-stream");
    response.addHeader("Content-Length", "" + file.length());
    InputStream fis = null;
    byte[] buffer = new byte[FILE_DOWNLOAD_BUFFER_SIZE];
    OutputStream toClient = null;
    try {
        fis = new BufferedInputStream(new FileInputStream(file));
        toClient = new BufferedOutputStream(response.getOutputStream());
        int readLength;
        while (((readLength = fis.read(buffer)) != -1)) {
            toClient.write(buffer, 0, readLength);
        }
        toClient.flush();
    } catch (FileNotFoundException e) {
        LOGGER.error("file not found:" + file.getAbsolutePath(), e);
        result = false;
    } catch (IOException e) {
        LOGGER.error("read file error:" + file.getAbsolutePath(), e);
        result = false;
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(toClient);
    }
    return result;
}

From source file:Main.java

public static String getMd5Hash(File file) {
    try {/*from ww w .j  a va2  s .c  om*/
        // CTS (6/15/2010) : stream file through digest instead of handing it the byte[]
        MessageDigest md = MessageDigest.getInstance("MD5");
        int chunkSize = 256;

        byte[] chunk = new byte[chunkSize];

        // Get the size of the file
        long lLength = file.length();

        if (lLength > Integer.MAX_VALUE) {
            Log.e(t, "File " + file.getName() + "is too large");
            return null;
        }

        int length = (int) lLength;

        InputStream is = null;
        is = new FileInputStream(file);

        int l = 0;
        for (l = 0; l + chunkSize < length; l += chunkSize) {
            is.read(chunk, 0, chunkSize);
            md.update(chunk, 0, chunkSize);
        }

        int remaining = length - l;
        if (remaining > 0) {
            is.read(chunk, 0, remaining);
            md.update(chunk, 0, remaining);
        }
        byte[] messageDigest = md.digest();

        BigInteger number = new BigInteger(1, messageDigest);
        String md5 = number.toString(16);
        while (md5.length() < 32)
            md5 = "0" + md5;
        is.close();
        return md5;

    } catch (NoSuchAlgorithmException e) {
        Log.e("MD5", e.getMessage());
        return null;

    } catch (FileNotFoundException e) {
        Log.e("No Cache File", e.getMessage());
        return null;
    } catch (IOException e) {
        Log.e("Problem reading from file", e.getMessage());
        return null;
    }

}

From source file:com.comcast.cdn.traffic_control.traffic_monitor.util.PeriodicResourceUpdater.java

static boolean filesEqual(final File a, final File b) throws IOException {
    if (!a.exists() && !b.exists()) {
        return true;
    }/*from www .  java 2 s .  c  o m*/
    if (!a.exists() || !b.exists()) {
        return false;
    }
    if (a.length() != b.length()) {
        return false;
    }
    FileInputStream fis = new FileInputStream(a);
    final String md5a = org.apache.commons.codec.digest.DigestUtils.md5Hex(fis);
    fis.close();
    fis = new FileInputStream(b);
    final String md5b = org.apache.commons.codec.digest.DigestUtils.md5Hex(fis);
    fis.close();
    if (md5a.equals(md5b)) {
        return true;
    }
    return false;
}

From source file:br.org.ipti.guigoh.util.DownloadService.java

public static synchronized void downloadFile(File file, String mimeType) {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext context = facesContext.getExternalContext();
    HttpServletResponse response = (HttpServletResponse) context.getResponse();
    response.setHeader("Content-Disposition", "attachment;filename=\"" + file.getName() + "\"");
    response.setContentLength((int) file.length());
    response.setContentType(mimeType);// w  w  w . jav  a 2  s.  co m
    try {
        OutputStream out;
        try (FileInputStream in = new FileInputStream(file)) {
            out = response.getOutputStream();
            byte[] buf = new byte[(int) file.length()];
            int count;
            while ((count = in.read(buf)) >= 0) {
                out.write(buf, 0, count);
            }
        }
        out.flush();
        out.close();
        facesContext.responseComplete();
    } catch (IOException ex) {
        System.out.println("Error in downloadFile: " + ex.getMessage());
    }
}

From source file:eu.scape_project.pit.util.FileUtils.java

/**
 * Read file of URL into file.//  w ww.  j  a  v a 2  s . com
 * @param url URL where the input file is located
 * @param ext 
 * @return Result file
 * @throws IOException 
 */
public static File urlToFile(URL url, String ext) throws IOException {
    File fOut = null;

    fOut = getTmpFile("fromurl", "." + ext);

    URLConnection uc = url.openConnection();
    logger.info("ContentType: " + uc.getContentType());
    InputStream in = uc.getInputStream();
    org.apache.commons.io.FileUtils.copyInputStreamToFile(in, fOut);
    logger.info("File of length " + fOut.length() + " created from URL " + url.toString());

    in.close();

    return fOut;
}

From source file:io.apicurio.studio.tools.release.ReleaseTool.java

/**
 * @param releaseArtifactFile//w  w w .  ja  v  a  2s.  c  om
 */
private static byte[] loadArtifactData(File releaseArtifactFile) throws Exception {
    System.out.println("Loading artifact content: " + releaseArtifactFile.getName());
    byte[] buffer = new byte[(int) releaseArtifactFile.length()];
    InputStream is = null;
    try {
        is = new FileInputStream(releaseArtifactFile);
        IOUtils.readFully(is, buffer);
        return buffer;
    } catch (IOException e) {
        throw new Exception(e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:net.sf.translate64.util.TranslateUtils.java

/**
 *  Returns the contents of the file in a byte array.
 *//*from  w w w .  j a va2 s .c o m*/
public static byte[] getBytesFromFile(File file) throws IOException {

    // create an input stream
    InputStream istream = new FileInputStream(file);

    // get the size
    long length = file.length();

    // check the length
    if (length > Integer.MAX_VALUE) {

        // file is too large
    }

    // create the byte array
    byte[] bytes = new byte[(int) length];

    // read in the bytes
    int offset = 0;

    // counter
    int numRead = 0;

    // do the trick
    while (offset < bytes.length && (numRead = istream.read(bytes, offset, bytes.length - offset)) >= 0) {
        offset += numRead;
    }

    // ensure all the bytes have been read in
    if (offset < bytes.length) {

        // throw an exception
        throw new IOException("Could not completely read file " + file.getName());
    }

    // close the input stream
    istream.close();

    // return bytes
    return bytes;
}

From source file:com.spstudio.common.image.ImageUtils.java

/**
 * ,?byte//w  w w.jav a 2s . co  m
 *
 * @return
 */
public static byte[] loadFile() {
    File file = new File("d:/touxiang.jpg");

    FileInputStream fis = null;
    ByteArrayOutputStream baos = null;
    byte[] data = null;

    try {
        fis = new FileInputStream(file);
        baos = new ByteArrayOutputStream((int) file.length());

        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = fis.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }

        data = baos.toByteArray();

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fis != null) {
                fis.close();
                fis = null;
            }

            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return data;
}

From source file:com.mtt.myapp.common.util.FileDownloadUtil.java

/**
 * Provide file download from the given file path.
 * @param response {@link javax.servlet.http.HttpServletResponse}
 * @param desFile file path/*w w  w . j a va  2s .  c o  m*/
 * @return true if succeeded
 */
public static boolean downloadFile(HttpServletResponse response, File desFile) {
    if (desFile == null || !desFile.exists()) {
        return false;
    }
    boolean result = true;
    response.reset();
    response.addHeader("Content-Disposition", "attachment;filename=" + desFile.getName());
    response.setContentType("application/octet-stream");
    response.addHeader("Content-Length", "" + desFile.length());
    InputStream fis = null;
    byte[] buffer = new byte[FILE_DOWNLOAD_BUFFER_SIZE];
    OutputStream toClient = null;
    try {
        fis = new BufferedInputStream(new FileInputStream(desFile));
        toClient = new BufferedOutputStream(response.getOutputStream());
        int readLength;
        while (((readLength = fis.read(buffer)) != -1)) {
            toClient.write(buffer, 0, readLength);
        }
        toClient.flush();
    } catch (FileNotFoundException e) {
        LOGGER.error("file not found:" + desFile.getAbsolutePath(), e);
        result = false;
    } catch (IOException e) {
        LOGGER.error("read file error:" + desFile.getAbsolutePath(), e);
        result = false;
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(toClient);
    }
    return result;
}

From source file:Main.java

/**
 * Reads the given file, translating {@link IOException} to a
 * {@link RuntimeException} of some sort.
 *
 * @param file {@code non-null;} the file to read
 * @return {@code non-null;} contents of the file
 *///from  w ww .  ja  va  2 s .  com
public static byte[] readFile(File file) {
    if (!file.exists()) {
        throw new RuntimeException(file + ": file not found");
    }

    if (!file.isFile()) {
        throw new RuntimeException(file + ": not a file");
    }

    if (!file.canRead()) {
        throw new RuntimeException(file + ": file not readable");
    }

    long longLength = file.length();
    int length = (int) longLength;
    if (length != longLength) {
        throw new RuntimeException(file + ": file too long");
    }

    byte[] result = new byte[length];

    try {
        FileInputStream in = new FileInputStream(file);
        int at = 0;
        while (length > 0) {
            int amt = in.read(result, at, length);
            if (amt == -1) {
                throw new RuntimeException(file + ": unexpected EOF");
            }
            at += amt;
            length -= amt;
        }
        in.close();
    } catch (IOException ex) {
        throw new RuntimeException(file + ": trouble reading", ex);
    }

    return result;
}