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:Main.java

public static ByteBuffer fromFile(File file) throws IOException {
    RandomAccessFile raf = null;/*from   www. j  av a2s.  c  o m*/
    FileChannel channel = null;
    try {
        raf = new RandomAccessFile(file, "r");
        channel = raf.getChannel();
        return channel.map(FileChannel.MapMode.READ_ONLY, 0, file.length()).load();
    } finally {
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException e) {
                // Ignored.
            }
        }
        if (raf != null) {
            try {
                raf.close();
            } catch (IOException e) {
                // Ignored.
            }
        }
    }
}

From source file:Main.java

public static void saveUtfFileWithBOM(File file, String content) throws IOException {
    BufferedWriter bw = null;/*from ww w  . ja v a2  s  . c o m*/
    OutputStreamWriter osw = null;

    FileOutputStream fos = new FileOutputStream(file);
    try {
        // write UTF8 BOM mark if file is empty
        if (file.length() < 1) {
            final byte[] bom = new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF };
            fos.write(bom);
        }

        osw = new OutputStreamWriter(fos, "UTF-8");
        bw = new BufferedWriter(osw);
        if (content != null) {
            bw.write(content);
        }
    } catch (IOException ex) {
        throw ex;
    } finally {
        try {
            bw.close();
            fos.close();
        } catch (Exception ex) {
        }
    }
}

From source file:Main.java

/**
 * Update content./*from  ww w. j a va 2s .  co m*/
 *
 * @param context
 *            context
 * @param sourceUri
 *            source uri
 * @param file
 *            output file
 * @return source uri
 */
public static Uri updateContent(Context context, Uri sourceUri, File file) {
    long now = System.currentTimeMillis() / MILLISEC_PER_SEC;
    final ContentValues values = new ContentValues();
    values.put(Images.Media.DATE_MODIFIED, now);
    values.put(Images.Media.DATE_ADDED, now);
    values.put(Images.Media.SIZE, file.length());
    context.getContentResolver().update(sourceUri, values, null, null);
    return sourceUri;
}

From source file:Main.java

public static void fastBufferFileCopy(File source, File target) {
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    long start = System.currentTimeMillis();
    FileInputStream fis = null;//from   w ww .j  av  a  2s .c  o m
    FileOutputStream fos = null;
    long size = source.length();
    try {
        fis = new FileInputStream(source);
        bis = new BufferedInputStream(fis);
        fos = new FileOutputStream(target);
        bos = new BufferedOutputStream(fos);

        byte[] barr = new byte[Math.min((int) size, 1 << 20)];
        int read = 0;
        while ((read = bis.read(barr)) != -1) {
            bos.write(barr, 0, read);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        close(fis);
        close(fos);
        close(bis);
        close(bos);
    }
    long end = System.currentTimeMillis();

    String srcPath = source.getAbsolutePath();
    Log.d("Copied " + srcPath + " to " + target,
            ", took " + (end - start) / 1000 + " ms, total size " + nf.format(size) + " Bytes, speed "
                    + ((end - start > 0) ? nf.format(size / (end - start)) : 0) + "KB/s");
}

From source file:in.goahead.apps.util.URLUtils.java

public static InputStream OpenURL(String url, String outputFile) throws MalformedURLException, IOException {
    File f = new File(outputFile);
    long skipBytes = 0;
    if (f.exists()) {
        skipBytes = f.length();
    }/*from   w ww  .  j a v a 2  s  .com*/
    return OpenURL(url, skipBytes);
}

From source file:Main.java

public static byte[] getFileAsBytes(File file) {
    byte[] bytes = null;
    InputStream is = null;/*from www  .j  av  a  2  s  . c  om*/
    try {
        is = new FileInputStream(file);

        // Get the size of the file
        long length = file.length();
        if (length > Integer.MAX_VALUE) {
            Log.e(t, "File " + file.getName() + "is too large");
            return null;
        }

        // Create the byte array to hold the data
        bytes = new byte[(int) length];

        // Read in the bytes
        int offset = 0;
        int read = 0;
        try {
            while (offset < bytes.length && read >= 0) {
                read = is.read(bytes, offset, bytes.length - offset);
                offset += read;
            }
        } catch (IOException e) {
            Log.e(t, "Cannot read " + file.getName());
            e.printStackTrace();
            return null;
        }

        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            try {
                throw new IOException("Could not completely read file " + file.getName());
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        return bytes;

    } catch (FileNotFoundException e) {
        Log.e(t, "Cannot find " + file.getName());
        e.printStackTrace();
        return null;

    } finally {
        // Close the input stream
        try {
            is.close();
        } catch (IOException e) {
            Log.e(t, "Cannot close input stream for " + file.getName());
            e.printStackTrace();
            return null;
        }
    }
}

From source file:Main.java

/**
 * Read the contents of a file and place them in
 * a string object.//from w  ww .j a  v  a 2 s  .c o m
 *
 * @param file path to file.
 * @return String contents of the file.
 */
public static String fileContentsToString(String file) {
    String contents = "";

    File f = null;
    try {
        f = new File(file);

        if (f.exists()) {
            FileReader fr = null;
            try {
                fr = new FileReader(f);
                char[] template = new char[(int) f.length()];
                fr.read(template);
                contents = new String(template);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fr != null) {
                    fr.close();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return contents;
}

From source file:FileViewer.java

/**
 * Returns the contents of the file in a byte array. 
 * @param file/*  ww w.  j  a  v  a 2s  . c o m*/
 * @return
 * @throws IOException
 */
public static byte[] getBytesFromFile(File file) throws IOException {
    InputStream is = new FileInputStream(file);

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

    // You cannot create an array using a long type.
    // It needs to be an int type.
    // Before converting to an int type, check
    // to ensure that file is not larger than Integer.MAX_VALUE.
    if (length > Integer.MAX_VALUE) {
        // File is too large
        throw new IllegalArgumentException("File is too large! (larger or equal to 2G)");
    }

    // Create the byte array to hold the data
    byte[] bytes = new byte[(int) length];

    // Read in the bytes
    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
        offset += numRead;
    }

    // Ensure all the bytes have been read in
    if (offset < bytes.length) {
        throw new IOException("Could not completely read file " + file.getName());
    }

    // Close the input stream and return bytes
    is.close();
    return bytes;
}

From source file:com.textocat.textokit.commons.util.CorpusUtils.java

/**
 * Partition corpus files specified by filters.
 *
 * @param corpusDir          corpus base directory
 * @param corpusFileFilter   filter for corpus files
 * @param corpusSubDirFilter filter for corpus subdirectories. If null subdirectories will
 *                           be ignored.
 * @param partitionsNumber/*from w ww. ja v  a  2 s  .  c  o m*/
 * @return list of file sets (partitions)
 */
public static List<Set<File>> partitionCorpusByFileSize(File corpusDir, IOFileFilter corpusFileFilter,
        IOFileFilter corpusSubDirFilter, int partitionsNumber) {
    log.info("Partitioning corpus {} with file filter {} and subdir filter {}...",
            new Object[] { corpusDir.getAbsolutePath(), corpusFileFilter, corpusSubDirFilter });
    // TODO implement an algorithm that is more robust to different file sizes
    // e.g. it should handle the case when there is no more files to include into the last partition
    if (partitionsNumber <= 0) {
        throw new IllegalArgumentException(String.format("Illegal number of partitions: %s", partitionsNumber));
    }
    if (!corpusDir.isDirectory()) {
        throw new IllegalArgumentException(String.format("%s is not existing directory", corpusDir));
    }
    final Deque<File> corpusFilesDeq;
    {
        List<File> corpusFiles = Lists
                .newArrayList(FileUtils.listFiles(corpusDir, corpusFileFilter, corpusSubDirFilter));
        // sort by decreasing size to smooth differences between parts
        Collections.sort(corpusFiles, SizeFileComparator.SIZE_REVERSE);
        corpusFilesDeq = Lists.newLinkedList(corpusFiles);
    }
    //
    int totalSize = 0;
    for (File cf : corpusFilesDeq) {
        totalSize += cf.length();
    }
    log.info("Corpus total size (bytes): {}", totalSize);
    List<FileBucket> buckets = Lists.newArrayListWithExpectedSize(partitionsNumber);
    // create empty parts
    for (int i = 0; i < partitionsNumber; i++) {
        buckets.add(new FileBucket());
    }
    while (!corpusFilesDeq.isEmpty()) {
        File cf = corpusFilesDeq.pop();
        buckets.get(0).add(cf);
        // resort: make the least bucket first
        Collections.sort(buckets);
    }
    // resort: make the largest bucket first
    Collections.sort(buckets, Collections.reverseOrder());
    // log
    log.info("Corpus {} has been partitioned by file sizes. Result partitions:\n{}", corpusDir,
            Joiner.on('\n').join(buckets));
    // transform
    List<Set<File>> result = Lists.newArrayList();
    for (FileBucket b : buckets) {
        result.add(b.getFiles());
    }
    // sanity checks
    if (result.size() != partitionsNumber || result.get(result.size() - 1).isEmpty()) {
        throw new IllegalStateException(
                "Illegal corpus partitioning result. Check previous log messages for details.");
    }
    return result;
}

From source file:com.siriusit.spezg.multilib.jsf.unit.UnitRegistrationBean.java

public static byte[] getBytesFromFile(File file) throws IOException {
    InputStream is = new FileInputStream(file);

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

    if (length > Integer.MAX_VALUE) {
        // File is too large
    }//from ww  w  .ja va2s  .  c o  m

    // Create the byte array to hold the data
    byte[] bytes = new byte[(int) length];

    // Read in the bytes
    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
        offset += numRead;
    }

    // Ensure all the bytes have been read in
    if (offset < bytes.length) {
        throw new IOException("Could not completely read file " + file.getName());
    }

    // Close the input stream and return bytes
    is.close();
    return bytes;
}