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:graphene.util.fs.FileUtils.java

private static byte[] loadFile(final File file, final InputStream is) throws IOException {
        final long length = file.length();
        if (length > Integer.MAX_VALUE) {
            return null;

        }// w w  w . j av  a2s  .co  m
        final byte[] bytes = new byte[(int) length];
        int offset = 0;
        int numRead = 0;
        while ((offset < bytes.length) && ((numRead = is.read(bytes, offset, bytes.length - offset)) >= 0)) {
            offset += numRead;
        }
        if (offset < bytes.length) {
            final StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("Could not completely read file ");
            stringBuilder.append(file.getName());
            throw new IOException(stringBuilder.toString());
        }
        return bytes;

    }

From source file:net.semanticmetadata.lire.utils.FileUtils.java

/**
 * Reads a whole file into a StringBuffer based on java.nio
 *
 * @param file          the file to open.
 * @param stringBuilder to write the File to.
 * @throws IOException//from  w  w  w.  j ava  2 s .c  o m
 */
public static void readWholeFile(File file, StringBuilder stringBuilder) throws IOException {
    long length = file.length();
    MappedByteBuffer in = new FileInputStream(file).getChannel().map(FileChannel.MapMode.READ_ONLY, 0, length);
    int i = 0;
    while (i < length)
        stringBuilder.append((char) in.get(i++));
}

From source file:com.alibaba.rocketmq.common.MixAll.java

public static final String file2String(final String fileName) {
    File file = new File(fileName);
    if (file.exists()) {
        char[] data = new char[(int) file.length()];
        boolean result = false;

        FileReader fileReader = null;
        try {/*from  w  ww  . j  a  v  a  2s.c  o  m*/
            fileReader = new FileReader(file);
            int len = fileReader.read(data);
            result = (len == data.length);
        } catch (IOException e) {
            // e.printStackTrace();
        } finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        if (result) {
            String value = new String(data);
            return value;
        }
    }
    return null;
}

From source file:com.jkoolcloud.tnt4j.streams.configure.state.AbstractFileStreamStateHandler.java

private static boolean isFileAvailable(File f) {
    return f != null && f.isFile() && f.length() > 0;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.util.FileUtil.java

public static boolean copyFile(final String sourceFilename, final String destFilename) {
    boolean success = false;
    FileChannel source = null;//from   w w w. j ava  2 s  . co m
    FileChannel destination = null;
    FileInputStream sourceStream = null;
    FileOutputStream destinationStream = null;
    final File destFile = new File(destFilename);
    final File sourceFile = new File(sourceFilename);
    try {
        final long size = sourceFile.length();
        sourceStream = new FileInputStream(sourceFile);
        destinationStream = new FileOutputStream(destFile);
        source = sourceStream.getChannel();
        destination = destinationStream.getChannel();
        long toTransfer = size;
        while (toTransfer > 0) {
            toTransfer -= source.transferTo(size - toTransfer, toTransfer, destination);
        }
        success = true;
    } catch (IOException iox) {
        try {
            logger.error(
                    "Unable to copy " + sourceFile.getCanonicalPath() + " to " + destFile.getCanonicalPath(),
                    iox);
        } catch (IOException iox2) {
            logger.error("Unable to copy " + sourceFile.getName() + " OR get the canonical name", iox2);
        }
    } finally {
        try {
            if (source != null) {
                source.close();
                source = null;
            }
            if (destination != null) {
                destination.close();
                destination = null;
            }
            if (sourceStream != null) {
                sourceStream.close();
                sourceStream = null;
            }
            if (destinationStream != null) {
                destinationStream.close();
                destinationStream = null;
            }
        } catch (IOException iox3) {
            logger.error("Unable to close stream?!?", iox3);
        }
    }
    return success;
}

From source file:Main.java

public static String uploadFile(String path) {
    String sourceFileUri = path;//from   w  w w. j a  v a 2  s . co m
    File file = new File(sourceFileUri);
    ByteArrayOutputStream objByteArrayOS = null;
    FileInputStream objFileIS = null;
    boolean isSuccess = false;
    String strAttachmentCoded = null;

    if (!file.isFile()) {
        Log.w(TAG, "Source File not exist :" + sourceFileUri);
    } else {
        try {
            objFileIS = new FileInputStream(file);
            objByteArrayOS = new ByteArrayOutputStream();
            byte[] byteBufferString = new byte[(int) file.length()];
            objFileIS.read(byteBufferString);

            byte[] byteBinaryData = Base64.encode(byteBufferString, Base64.DEFAULT);
            strAttachmentCoded = new String(byteBinaryData);

            isSuccess = true;
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("Upload file to server", "error: " + e.getMessage(), e);
        } finally {
            try {
                objByteArrayOS.close();
                objFileIS.close();
            } catch (IOException e) {
                Log.e(TAG, "Error : " + e.getMessage());
            }
        }
    }

    if (isSuccess) {
        return strAttachmentCoded;
    } else {
        return "No Picture";
    }
}

From source file:com.geekandroid.sdk.pay.utils.Util.java

public static byte[] readFromFile(String fileName, int offset, int len) {
    if (fileName == null) {
        return null;
    }//from  ww  w.j av  a2s . c o m

    File file = new File(fileName);
    if (!file.exists()) {
        Log.i(TAG, "readFromFile: file not found");
        return null;
    }

    if (len == -1) {
        len = (int) file.length();
    }

    Log.d(TAG, "readFromFile : offset = " + offset + " len = " + len + " offset + len = " + (offset + len));

    if (offset < 0) {
        Log.e(TAG, "readFromFile invalid offset:" + offset);
        return null;
    }
    if (len <= 0) {
        Log.e(TAG, "readFromFile invalid len:" + len);
        return null;
    }
    if (offset + len > (int) file.length()) {
        Log.e(TAG, "readFromFile invalid file len:" + file.length());
        return null;
    }

    byte[] b = null;
    try {
        RandomAccessFile in = new RandomAccessFile(fileName, "r");
        b = new byte[len]; // ??
        in.seek(offset);
        in.readFully(b);
        in.close();

    } catch (Exception e) {
        Log.e(TAG, "readFromFile : errMsg = " + e.getMessage());
        e.printStackTrace();
    }
    return b;
}

From source file:FileHelper.java

private static void copyFile(File srcFile, File destFile, long chunkSize) throws IOException {
    FileInputStream is = null;/*from  w w  w.j  a v  a 2s. c  om*/
    FileOutputStream os = null;
    try {
        is = new FileInputStream(srcFile);
        FileChannel iChannel = is.getChannel();
        os = new FileOutputStream(destFile, false);
        FileChannel oChannel = os.getChannel();
        long doneBytes = 0L;
        long todoBytes = srcFile.length();
        while (todoBytes != 0L) {
            long iterationBytes = Math.min(todoBytes, chunkSize);
            long transferredLength = oChannel.transferFrom(iChannel, doneBytes, iterationBytes);
            if (iterationBytes != transferredLength) {
                throw new IOException("Error during file transfer: expected " + iterationBytes + " bytes, only "
                        + transferredLength + " bytes copied.");
            }
            doneBytes += transferredLength;
            todoBytes -= transferredLength;
        }
    } finally {
        if (is != null) {
            is.close();
        }
        if (os != null) {
            os.close();
        }
    }
    boolean successTimestampOp = destFile.setLastModified(srcFile.lastModified());
    if (!successTimestampOp) {
        System.out.println("Could not change timestamp for {}. Index synchronization may be slow. " + destFile);
    }
}

From source file:modnlp.capte.AlignerUtils.java

@SuppressWarnings("deprecation")
/* This method creates the HTTP connection to the server 
 * and sends the POST request with the two files for alignment,
 * /*from ww  w.  j  a va  2 s. c o  m*/
 * The server returns the aligned file as the response to the post request, 
 * which is delimited by the tag <beginalignment> which separates the file
 * from the rest of the POST request
 * 
 * 
 * 
 */
public static String MultiPartFileUpload(String source, String target) throws IOException {
    String response = "";
    String serverline = System.getProperty("capte.align.server"); //"http://ronaldo.cs.tcd.ie:80/~gplynch/aling.cgi";   
    PostMethod filePost = new PostMethod(serverline);
    // Send any XML file as the body of the POST request
    File f1 = new File(source);
    File f2 = new File(target);
    System.out.println(f1.getName());
    System.out.println(f2.getName());
    System.out.println("File1 Length = " + f1.length());
    System.out.println("File2 Length = " + f2.length());
    Part[] parts = {

            new StringPart("param_name", "value"), new FilePart(f2.getName(), f2),
            new FilePart(f1.getName(), f1) };
    filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
    HttpClient client = new HttpClient();
    int status = client.executeMethod(filePost);
    String res = "";
    InputStream is = filePost.getResponseBodyAsStream();
    Header[] heads = filePost.getResponseHeaders();
    Header[] feet = filePost.getResponseFooters();
    BufferedInputStream bis = new BufferedInputStream(is);

    String datastr = null;
    StringBuffer sb = new StringBuffer();
    byte[] bytes = new byte[8192]; // reading as chunk of 8192
    int count = bis.read(bytes);
    while (count != -1 && count <= 8192) {
        datastr = new String(bytes, "UTF8");

        sb.append(datastr);
        count = bis.read(bytes);
    }

    bis.close();
    res = sb.toString();

    System.out.println("----------------------------------------");
    System.out.println("Status is:" + status);
    //System.out.println(res);
    /* for debugging
    for(int i = 0 ;i < heads.length ;i++){
      System.out.println(heads[i].toString());
                   
    }
    for(int j = 0 ;j < feet.length ;j++){
      System.out.println(feet[j].toString());
                   
    }
    */
    filePost.releaseConnection();
    String[] handle = res.split("<beginalignment>");
    //Check for errors in the header
    // System.out.println(handle[0]);
    //Return the required text
    String ho = "";
    if (handle.length < 2) {
        System.out.println("Server error during alignment, check file encodings");
        ho = "error";
    } else {
        ho = handle[1];
    }
    return ho;

}

From source file:net.pms.util.OpenSubtitle.java

public static Map<String, Object> findSubs(File f, RendererConfiguration r) throws IOException {
    Map<String, Object> res = findSubs(getHash(f), f.length(), null, null, r);
    if (res.isEmpty()) { // no good on hash! try imdb
        String imdb = ImdbUtil.extractImdb(f);
        if (StringUtils.isEmpty(imdb)) {
            imdb = fetchImdbId(f);/*w ww  .j  ava  2s  .co m*/
        }
        res = findSubs(null, 0, imdb, null, r);
    }
    if (res.isEmpty()) { // final try, use the name
        res = querySubs(f.getName(), r);
    }
    return res;
}