Example usage for java.nio.channels FileChannel size

List of usage examples for java.nio.channels FileChannel size

Introduction

In this page you can find the example usage for java.nio.channels FileChannel size.

Prototype

public abstract long size() throws IOException;

Source Link

Document

Returns the current size of this channel's file.

Usage

From source file:org.wandora.application.gui.topicpanels.ProcessingTopicPanel.java

private String buildSource(String sketch) {
    boolean useTemplate = false; // maybe make this an option in the future

    try {//from   ww  w  .java2s  .  c  o m
        //            classIdentifier = System.currentTimeMillis();
        if (useTemplate) {
            //                processingClassName="SketchTemplate";

            String sketchTemplate = "";
            FileInputStream stream = new FileInputStream(new File(sketchPath + "SketchTemplate.java"));

            try {
                FileChannel fc = stream.getChannel();
                MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
                /* Instead of using default, pass in a decoder. */
                sketchTemplate = Charset.defaultCharset().decode(bb).toString();
            } finally {
                stream.close();
            }
            String upperPart = sketchTemplate.substring(0, sketchTemplate.indexOf(tempReplaceStart) + 1);
            linesBeforeCode = upperPart.split(System.getProperty("line.separator")).length - 1;
            //System.out.println("Lines before code "+linesBeforeCode);

            charactersBefore = sketchTemplate.indexOf(tempReplaceStart);
            //temp = temp.substring(temp.indexOf("\n"));

            String fullSource = sketchTemplate.substring(0, sketchTemplate.indexOf(tempReplaceStart)) + sketch
                    + sketchTemplate.substring(sketchTemplate.indexOf(tempReplaceEnd) + tempReplaceEnd.length(),
                            sketchTemplate.length());

            //                fullSource = fullSource.replaceAll("(?:SketchTemplate)", processingClassName+classIdentifier);
            //                fullSource = fullSource.replaceFirst("(?:PApplet)", "SketchTemplate");
            return fullSource;
        } else {
            // (?m) turns on multi-line mode so ^ and $ match line start and end
            Pattern p = Pattern.compile("(?m)^\\s*package\\s+processing\\s*;\\s*$");
            if (!p.matcher(sketch).find()) {
                throw new Exception(
                        "The sketch file must be defined to be in the \"processing\" package. Add \"package processing;\" at the start of the sketch or modify the existing package declaration.");
            }

            return sketch;
        }
    } catch (Exception ex) {
        Logger.getLogger(ProcessingTopicPanel.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
    }
    return null;
}

From source file:com.dotmarketing.util.ImportExportUtil.java

/**
 *
 * @param zipFile//from  w  ww.  j a  v  a 2  s  .co m
 * @return
 */
public boolean validateZipFile(File zipFile) {

    String tempdir = getBackupTempFilePath();
    try {
        deleteTempFiles();

        File ftempDir = new File(tempdir);
        ftempDir.mkdirs();
        File tempZip = new File(tempdir + File.separator + zipFile.getName());
        tempZip.createNewFile();
        FileChannel ic = new FileInputStream(zipFile).getChannel();
        FileChannel oc = new FileOutputStream(tempZip).getChannel();

        // to handle huge zipfiles
        ic.transferTo(0, ic.size(), oc);

        ic.close();
        oc.close();

        /*
         * Unzip zipped backups
         */
        if (zipFile != null && zipFile.getName().toLowerCase().endsWith(".zip")) {
            ZipFile z = new ZipFile(zipFile);
            ZipUtil.extract(z, new File(backupTempFilePath));
        }
        return true;

    } catch (Exception e) {
        Logger.error(this, "Error with file", e);
        return false;
    }
}

From source file:jackpal.androidterm.Term.java

private void copyFileToClipboard(String filename) {
    if (filename == null)
        return;//from   ww w.ja  v  a2 s.  c om
    FileInputStream fis;
    try {
        fis = new FileInputStream(filename);
        FileChannel fc = fis.getChannel();
        try {
            ByteBuffer bbuf;
            bbuf = fc.map(FileChannel.MapMode.READ_ONLY, 0, (int) fc.size());
            // Create a read-only CharBuffer on the file
            CharBuffer cbuf = Charset.forName("UTF-8").newDecoder().decode(bbuf);
            String str = cbuf.toString();
            ClipboardManagerCompat clip = ClipboardManagerCompatFactory.getManager(getApplicationContext());
            clip.setText(str);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.wso2.developerstudio.eclipse.registry.apim.views.RegistryBrowserAPIMView.java

private void copyFileToFile(File source, File dest) throws IOException {
    FileChannel inputChannel = null;
    FileChannel outputChannel = null;
    try {/*  w  w w . java  2 s  .c o  m*/
        inputChannel = new FileInputStream(source).getChannel();
        outputChannel = new FileOutputStream(dest).getChannel();
        outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
    } finally {
        inputChannel.close();
        outputChannel.close();
    }
}

From source file:org.sakaiproject.search.index.impl.JDBCClusterIndexStore.java

/**
 * @param packetStream// w  w w.  j  a v  a2  s .  c  o m
 * @param sharedStream
 * @throws IOException
 */
private void doBlockedStream(FileChannel from, FileChannel to) throws IOException {
    to.position(0);
    long size = from.size();
    for (long pos = 0; pos < size;) {
        long count = size - pos;
        if (count > MAX_BLOCK_SIZE) {
            count = MAX_BLOCK_SIZE;

        }

        to.position(pos);
        long cpos = to.position();
        log.debug("NIOTransfering |" + count + "| bytes from |" + pos + "| to |" + cpos + "|");
        long t = to.transferFrom(from, pos, count);
        pos = pos + t;
    }
    log.debug("  Final Size Source        " + from.size());
    log.debug("  Final Size Destination   " + to.size());
}

From source file:com.vegnab.vegnab.MainVNActivity.java

public void copyFile(File src, File dst) throws IOException {
    FileInputStream in = new FileInputStream(src);
    FileOutputStream out = new FileOutputStream(dst);
    FileChannel fromChannel = null, toChannel = null;
    try {/*from w  w  w  .j  av a  2  s .co m*/
        fromChannel = in.getChannel();
        toChannel = out.getChannel();
        fromChannel.transferTo(0, fromChannel.size(), toChannel);
    } finally {
        if (fromChannel != null)
            fromChannel.close();
        if (toChannel != null)
            toChannel.close();
    }
    in.close();
    out.close();
    // must do following or file is not visible externally
    MediaScannerConnection.scanFile(getApplicationContext(), new String[] { dst.getAbsolutePath() }, null,
            null);
}

From source file:com.example.util.FileUtils.java

/**
 * Internal copy file method./*w  w w  .j a va2  s  .c om*/
 * 
 * @param srcFile  the validated source file, must not be {@code null}
 * @param destFile  the validated destination file, must not be {@code null}
 * @param preserveFileDate  whether to preserve the file date
 * @throws IOException if an error occurs
 */
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
    if (destFile.exists() && destFile.isDirectory()) {
        throw new IOException("Destination '" + destFile + "' exists but is a directory");
    }

    FileInputStream fis = null;
    FileOutputStream fos = null;
    FileChannel input = null;
    FileChannel output = null;
    try {
        fis = new FileInputStream(srcFile);
        fos = new FileOutputStream(destFile);
        input = fis.getChannel();
        output = fos.getChannel();
        long size = input.size();
        long pos = 0;
        long count = 0;
        while (pos < size) {
            count = size - pos > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos;
            pos += output.transferFrom(input, pos, count);
        }
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(fis);
    }

    if (srcFile.length() != destFile.length()) {
        throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'");
    }
    if (preserveFileDate) {
        destFile.setLastModified(srcFile.lastModified());
    }
}

From source file:com.matteoveroni.model.copy.FileUtils.java

/**
 * Internal copy file method./*ww w. ja  va2  s.  c o  m*/
 * 
 * @param srcFile  the validated source file, must not be {@code null}
 * @param destFile  the validated destination file, must not be {@code null}
 * @param preserveFileDate  whether to preserve the file date
 * @throws IOException if an error occurs
 */
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
    if (destFile.exists() && destFile.isDirectory()) {
        throw new IOException("Destination '" + destFile + "' exists but is a directory");
    }

    FileInputStream fis = null;
    FileOutputStream fos = null;
    FileChannel input = null;
    FileChannel output = null;
    try {
        bytesTransferedTotal = 0;
        fis = new FileInputStream(srcFile);
        fos = new FileOutputStream(destFile);
        input = fis.getChannel();
        output = fos.getChannel();
        long size = input.size();
        long pos = 0;
        long count = 0;
        while (pos < size) {
            count = size - pos > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos;

            //pos += output.transferFrom(input, pos, count);

            //Split into into deceleration and assignment to count bytes transfered
            long bytesTransfered = output.transferFrom(input, pos, count);
            //complete original method
            pos += bytesTransfered;
            //update total bytes copied, so it can be used to calculate progress
            bytesTransferedTotal += bytesTransfered;
            System.out.println((int) Math.floor((100.0 / size) * bytesTransferedTotal) + "%");
        }
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(fis);
    }

    if (srcFile.length() != destFile.length()) {
        throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'");
    }
    if (preserveFileDate) {
        destFile.setLastModified(srcFile.lastModified());
    }
}

From source file:com.benefit.buy.library.http.query.AbstractAQuery.java

/**
 * Create a temporary file on EXTERNAL storage (sdcard) that holds the cached content of the url. Returns null if
 * url is not cached, or the system cannot create such file (sdcard is absent, such as in emulator). The returned
 * file is accessable to all apps, therefore it is ideal for sharing content (such as photo) via the intent
 * mechanism. <br>//from ww  w . j  a v a 2  s .  c o  m
 * <br>
 * Example Usage:
 * 
 * <pre>
 * Intent intent = new Intent(Intent.ACTION_SEND);
 * intent.setType(&quot;image/jpeg&quot;);
 * intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
 * startActivityForResult(Intent.createChooser(intent, &quot;Share via:&quot;), 0);
 * </pre>
 * 
 * <br>
 * The temp file will be deleted when AQUtility.cleanCacheAsync is invoked, or the file can be explicitly deleted
 * after use.
 * @param url The url of the desired cached content.
 * @param filename The desired file name, which might be used by other apps to describe the content, such as an
 *            email attachment.
 * @return temp file
 */
public File makeSharedFile(String url, String filename) {
    File file = null;
    try {
        File cached = getCachedFile(url);
        if (cached != null) {
            File temp = AQUtility.getTempDir();
            if (temp != null) {
                file = new File(temp, filename);
                file.createNewFile();
                FileInputStream fis = new FileInputStream(cached);
                FileOutputStream fos = new FileOutputStream(file);
                FileChannel ic = fis.getChannel();
                FileChannel oc = fos.getChannel();
                try {
                    ic.transferTo(0, ic.size(), oc);
                } finally {
                    AQUtility.close(fis);
                    AQUtility.close(fos);
                    AQUtility.close(ic);
                    AQUtility.close(oc);
                }
            }
        }
    } catch (Exception e) {
        AQUtility.debug(e);
    }
    return file;
}

From source file:semlink.apps.uvig.Generator.java

/**
 * Performs a low-level copy of one file into another.
 *
 * @param src  the source file/*from w ww. ja  v a 2  s .com*/
 * @param dest the destination file
 * @see        uvi.Generator#copySupplementalFiles()
 */
private static void copyFile(File src, File dest) {
    try {
        FileChannel sourceChannel = new FileInputStream(src).getChannel();
        FileChannel destinationChannel = new FileOutputStream(dest).getChannel();

        sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);

        sourceChannel.close();
        destinationChannel.close();
    } catch (Exception e) {
        eprintln("ERROR: Problem copying image file  \"" + src.getName() + "\" to output directory.  "
                + e.getMessage());
    }
}