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:com.marklogic.client.functionaltest.BasicJavaClientREST.java

/**
 * Copy Files from One location to Other
 * @param Source File//from w  ww.  j  a  v a  2  s  .  co  m
 * @param target File
 * @param Boolean Value
 * @throws FileNotFoundException
 */
public void copyWithChannels(File aSourceFile, File aTargetFile, boolean aAppend) {
    //log("Copying files with channels.");
    //ensureTargetDirectoryExists(aTargetFile.getParentFile());
    FileChannel inChannel = null;
    FileChannel outChannel = null;
    FileInputStream inStream = null;
    FileOutputStream outStream = null;
    try {
        try {
            inStream = new FileInputStream(aSourceFile);
            inChannel = inStream.getChannel();
            outStream = new FileOutputStream(aTargetFile, aAppend);
            outChannel = outStream.getChannel();
            long bytesTransferred = 0;
            //defensive loop - there's usually only a single iteration :
            while (bytesTransferred < inChannel.size()) {
                bytesTransferred += inChannel.transferTo(0, inChannel.size(), outChannel);
            }
        } finally {
            //being defensive about closing all channels and streams 
            if (inChannel != null)
                inChannel.close();
            if (outChannel != null)
                outChannel.close();
            if (inStream != null)
                inStream.close();
            if (outStream != null)
                outStream.close();
        }
    } catch (FileNotFoundException ex) {
        System.out.println("File not found: " + ex);
    } catch (IOException ex) {
        System.out.println(ex);
    }
}

From source file:com.cisco.dvbu.ps.common.util.CommonUtils.java

/**
 * The copyFile method is used to copy files from a source to a destination folder.
 * //from ww w  .j a v a 2 s .c o  m
 * @param fromFilePath
 * @param toFilePath
 * @throws ValidationException
 */
public static void copyFile(String fromFilePath, String toFilePath, boolean forceCopy)
        throws ValidationException {

    FileChannel srcChannel = null;
    FileChannel dstChannel = null;
    boolean fileExists = fileExists(toFilePath);

    if (forceCopy && fileExists) {
        removeFile(toFilePath);
        fileExists = fileExists(toFilePath);
    }

    if ((!fileExists) || (forceCopy && fileExists)) {
        try {
            // Create channel on the source
            srcChannel = new FileInputStream(fromFilePath).getChannel();

            // Create channel on the destination
            dstChannel = new FileOutputStream(toFilePath).getChannel();

            // Force the copy - added to overcome copy error
            dstChannel.force(true);

            // Copy file contents from source to destination
            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());

        } catch (IOException e) {
            String message = "Could not copy file " + fromFilePath + ".An error was encountered: "
                    + e.toString();
            throw new ValidationException(message, e);
        } finally {
            try {
                // Close the channels
                if (srcChannel != null)
                    srcChannel.close();
                if (dstChannel != null)
                    dstChannel.close();
                srcChannel = null;
                dstChannel = null;
            } catch (IOException e) {
                String message = "Could not copy file " + fromFilePath
                        + ".  Error encountered while closing source and destination channels: " + e.toString();
                throw new ValidationException(message, e);
            }
        }
    }
}

From source file:com.ezac.gliderlogs.FlightOverviewActivity.java

@SuppressLint("SimpleDateFormat")
public void GliderLogToDB(String DBPath, String DB, String device) {
    // format date
    SimpleDateFormat TSD = new SimpleDateFormat("yyyyMMdd_kkss");
    SimpleDateFormat DIR = new SimpleDateFormat("yyyy/MM_dd");
    Date myDate = new Date();
    String backupDBPath = device + "_" + TSD.format(myDate);
    String TS_DIR = DIR.format(myDate);
    // to internal sdcard
    File dir = new File(Environment.getExternalStorageDirectory() + "/Download/" + TS_DIR);
    if (!dir.exists() || !dir.isDirectory()) {
        dir.mkdir();/*from  w  w w.  j  a v  a 2s.c  o  m*/
    }
    File data = Environment.getDataDirectory();
    // create a file channel object
    FileChannel src = null;
    FileChannel des = null;
    File currentDB = new File(data + "/data/" + DBPath + "/databases/", DB);
    File backupDB = new File(dir, backupDBPath);
    try {
        backupDB.delete();
        src = new FileInputStream(currentDB).getChannel();
        des = new FileOutputStream(backupDB).getChannel();
        des.transferFrom(src, 0, src.size());
        src.close();
        des.close();
    } catch (IOException e) {
        Log.d(TAG, e.toString());
        e.printStackTrace();
    }
}

From source file:com.tandong.sa.aq.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).
 * /*  w  w  w .j av a 2  s .co m*/
 * The returned file is accessable to all apps, therefore it is ideal for sharing content (such as photo) via the intent mechanism.
 * 
 * <br>
 * <br>
 * Example Usage:
 * 
 * <pre>
 *   Intent intent = new Intent(Intent.ACTION_SEND);
 *   intent.setType("image/jpeg");
 *   intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
 *   startActivityForResult(Intent.createChooser(intent, "Share via:"), 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();

                FileChannel ic = new FileInputStream(cached).getChannel();
                FileChannel oc = new FileOutputStream(file).getChannel();
                try {
                    ic.transferTo(0, ic.size(), oc);
                } finally {
                    if (ic != null)
                        ic.close();
                    if (oc != null)
                        oc.close();
                }

            }
        }

    } catch (Exception e) {
        AQUtility.debug(e);
    }

    return file;
}

From source file:com.shinymayhem.radiopresets.ServiceRadioPlayer.java

public void copyLog() {
    //String path = Environment.getExternalStorageDirectory().getAbsolutePath();
    String path = getExternalFilesDir(null).getAbsolutePath();

    File src = getFileStreamPath(ActivityLogger.LOG_FILENAME);
    File dst = new File(path + File.separator + ActivityLogger.LOG_FILENAME);
    try {/*from  w ww  .ja va  2s .  c  o  m*/
        if (dst.createNewFile()) {
            if (LOCAL_LOGV)
                log("sd file created", "v");
        } else {
            if (LOCAL_LOGV)
                log("sd file exists?", "v");
        }
    } catch (IOException e2) {
        log("sd file error", "e");
        Toast.makeText(this, "sd file error", Toast.LENGTH_SHORT).show();
        e2.printStackTrace();
    }

    FileChannel in = null;
    FileChannel out = null;
    try {
        in = new FileInputStream(src).getChannel();
    } catch (FileNotFoundException e1) {
        log("in file not found", "e");
        Toast.makeText(this, "in file not found", Toast.LENGTH_SHORT).show();
        e1.printStackTrace();
    }
    try {
        out = new FileOutputStream(dst).getChannel();
    } catch (FileNotFoundException e1) {
        log("out file not found", "e");
        Toast.makeText(this, "out file not found", Toast.LENGTH_SHORT).show();
        e1.printStackTrace();
    }

    try {
        in.transferTo(0, in.size(), out);
        if (LOCAL_LOGD)
            log("log file copied to " + path + File.separator + ActivityLogger.LOG_FILENAME, "d");
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
        clearLog();
    } catch (IOException e) {
        log("error copying log file", "e");
        Toast.makeText(this, "error copying log file", Toast.LENGTH_SHORT).show();
        if (LOCAL_LOGV)
            e.printStackTrace();
    } finally {

    }
}

From source file:com.androidquery.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).
 * /*from   w w w .j a  va 2 s. com*/
 * The returned file is accessable to all apps, therefore it is ideal for sharing content (such as photo) via the intent mechanism.
 * 
 * <br>
 * <br>
 * Example Usage:
 * 
 * <pre>
 *   Intent intent = new Intent(Intent.ACTION_SEND);
 *   intent.setType("image/jpeg");
 *   intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
 *   startActivityForResult(Intent.createChooser(intent, "Share via:"), 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:edu.harvard.iq.dvn.core.web.servlet.FileDownloadServlet.java

public void streamData(FileChannel in, WritableByteChannel out, String varHeader) {

    long position = 0;
    long howMany = 32 * 1024;

    try {/*w  ww.j a va 2 s.com*/
        // If we are streaming a TAB-delimited file, we will need to add the
        // variable header line:

        if (varHeader != null) {
            ByteBuffer varHeaderByteBuffer = ByteBuffer.wrap(varHeader.getBytes());
            out.write(varHeaderByteBuffer);
        }

        while (position < in.size()) {
            in.transferTo(position, howMany, out);
            position += howMany;
        }

        in.close();
        out.close();
    } catch (IOException ex) {
        // whatever. we don't care at this point.
    }

}

From source file:com.MainFiles.Functions.java

public int createStan() {
    int x = 0;/*from ww w  . j  a  v a 2s .c o  m*/

    String filename = COUNT_FILE;
    File inwrite = new File(filename);

    // Get a file channel for the file
    try {
        FileChannel channel = new RandomAccessFile(inwrite, "rw").getChannel();
        // Use the file channel to create a lock on the file.
        // This method blocks until it can retrieve the lock.
        FileLock lock = channel.lock();
        //  if(!inwrite.exists()) {
        String s = "";
        try {
            int fileSize = (int) channel.size();
            //    System.out.println("int is" + fileSize);
            ByteBuffer bafa = ByteBuffer.allocate(fileSize);
            int numRead = 0;
            while (numRead >= 0) {
                numRead = channel.read(bafa);
                bafa.rewind();
                for (int i = 0; i < numRead; i++) {
                    int b = (int) bafa.get();
                    char c = (char) b;
                    s = s + c;
                }
            }

            x = Integer.parseInt(s);
            if (x > 999999) {
                x = 100000;
            } else if (x < 100000) {
                x = 100000;
            }
            x = ++x;
            String xx = String.valueOf(x);
            byte[] yy = xx.getBytes();
            channel.truncate(0);
            channel.write(ByteBuffer.wrap(yy));
            // channel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        lock.release();
        // Close the file
        channel.close();
    } catch (FileNotFoundException e) {
        String message = "The file " + inwrite.getName() + " does not exist. So no input can be written on it";
        System.out.println(message);
        e.printStackTrace();
        //log to error file
    } catch (IOException e) {
        System.out.println("Problem writing to the logfile " + inwrite.getName());

    }

    filename = "";
    return x;
}

From source file:org.alfresco.repo.search.impl.lucene.index.IndexInfo.java

private boolean checkVersion(FileChannel channel) throws IOException {
    if (channel.size() > 0) {
        channel.position(0);/*from  ww w. j a v a  2 s  . c o m*/
        ByteBuffer buffer;

        if (useNIOMemoryMapping) {
            MappedByteBuffer mbb = channel.map(MapMode.READ_ONLY, 0, 8);
            mbb.load();
            buffer = mbb;
        } else {
            buffer = ByteBuffer.wrap(new byte[8]);
            channel.read(buffer);
            buffer.position(0);
        }

        buffer.position(0);
        long onDiskVersion = buffer.getLong();
        return (version == onDiskVersion);
    }
    return (version == 0);
}

From source file:org.alfresco.repo.search.impl.lucene.index.IndexInfo.java

private void setStatusFromFile(FileChannel channel) throws IOException {
    if (channel.size() > 0) {
        channel.position(0);/*from   w  w  w . j av  a  2 s . com*/
        ByteBuffer buffer;

        if (useNIOMemoryMapping) {
            MappedByteBuffer mbb = channel.map(MapMode.READ_ONLY, 0, channel.size());
            mbb.load();
            buffer = mbb;
        } else {
            buffer = ByteBuffer.wrap(new byte[(int) channel.size()]);
            channel.read(buffer);
            buffer.position(0);
        }

        buffer.position(0);
        long onDiskVersion = buffer.getLong();
        if (version != onDiskVersion) {
            CRC32 crc32 = new CRC32();
            crc32.update((int) (onDiskVersion >>> 32) & 0xFFFFFFFF);
            crc32.update((int) (onDiskVersion >>> 0) & 0xFFFFFFFF);
            int size = buffer.getInt();
            crc32.update(size);
            LinkedHashMap<String, IndexEntry> newIndexEntries = new LinkedHashMap<String, IndexEntry>();
            // Not all state is saved some is specific to this index so we
            // need to add the transient stuff.
            // Until things are committed they are not shared unless it is
            // prepared
            for (int i = 0; i < size; i++) {
                String indexTypeString = readString(buffer, crc32);
                IndexType indexType;
                try {
                    indexType = IndexType.valueOf(indexTypeString);
                } catch (IllegalArgumentException e) {
                    throw new IOException("Invalid type " + indexTypeString);
                }

                String name = readString(buffer, crc32);

                String parentName = readString(buffer, crc32);

                String txStatus = readString(buffer, crc32);
                TransactionStatus status;
                try {
                    status = TransactionStatus.valueOf(txStatus);
                } catch (IllegalArgumentException e) {
                    throw new IOException("Invalid status " + txStatus);
                }

                String mergeId = readString(buffer, crc32);

                long documentCount = buffer.getLong();
                crc32.update((int) (documentCount >>> 32) & 0xFFFFFFFF);
                crc32.update((int) (documentCount >>> 0) & 0xFFFFFFFF);

                long deletions = buffer.getLong();
                crc32.update((int) (deletions >>> 32) & 0xFFFFFFFF);
                crc32.update((int) (deletions >>> 0) & 0xFFFFFFFF);

                byte deleteOnlyNodesFlag = buffer.get();
                crc32.update(deleteOnlyNodesFlag);
                boolean isDeletOnlyNodes = deleteOnlyNodesFlag == 1;

                if (!status.isTransient()) {
                    newIndexEntries.put(name, new IndexEntry(indexType, name, parentName, status, mergeId,
                            documentCount, deletions, isDeletOnlyNodes));
                }
            }
            long onDiskCRC32 = buffer.getLong();
            if (crc32.getValue() == onDiskCRC32) {
                for (IndexEntry entry : indexEntries.values()) {
                    if (entry.getStatus().isTransient()) {
                        newIndexEntries.put(entry.getName(), entry);
                    }
                }
                version = onDiskVersion;
                indexEntries = newIndexEntries;
            } else {
                throw new IOException("Invalid file check sum");
            }
        }
    }

}