Example usage for java.nio.channels FileChannel force

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

Introduction

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

Prototype

public abstract void force(boolean metaData) throws IOException;

Source Link

Document

Forces any updates to this channel's file to be written to the storage device that contains it.

Usage

From source file:Lock.java

public static void main(String args[]) throws IOException, InterruptedException {
    RandomAccessFile file = null; // The file we'll lock
    FileChannel f = null; // The channel to the file
    FileLock lock = null; // The lock object we hold

    try { // The finally clause closes the channel and releases the lock
        // We use a temporary file as the lock file.
        String tmpdir = System.getProperty("java.io.tmpdir");
        String filename = Lock.class.getName() + ".lock";
        File lockfile = new File(tmpdir, filename);

        // Create a FileChannel that can read and write that file.
        // Note that we rely on the java.io package to open the file,
        // in read/write mode, and then just get a channel from it.
        // This will create the file if it doesn't exit. We'll arrange
        // for it to be deleted below, if we succeed in locking it.
        file = new RandomAccessFile(lockfile, "rw");
        f = file.getChannel();// w  w  w. j  a  v a 2  s .  c  o m

        // Try to get an exclusive lock on the file.
        // This method will return a lock or null, but will not block.
        // See also FileChannel.lock() for a blocking variant.
        lock = f.tryLock();

        if (lock != null) {
            // We obtained the lock, so arrange to delete the file when
            // we're done, and then write the approximate time at which
            // we'll relinquish the lock into the file.
            lockfile.deleteOnExit(); // Just a temporary file

            // First, we need a buffer to hold the timestamp
            ByteBuffer bytes = ByteBuffer.allocate(8); // a long is 8 bytes

            // Put the time in the buffer and flip to prepare for writing
            // Note that many Buffer methods can be "chained" like this.
            bytes.putLong(System.currentTimeMillis() + 10000).flip();

            f.write(bytes); // Write the buffer contents to the channel
            f.force(false); // Force them out to the disk
        } else {
            // We didn't get the lock, which means another instance is
            // running. First, let the user know this.
            System.out.println("Another instance is already running");

            // Next, we attempt to read the file to figure out how much
            // longer the other instance will be running. Since we don't
            // have a lock, the read may fail or return inconsistent data.
            try {
                ByteBuffer bytes = ByteBuffer.allocate(8);
                f.read(bytes); // Read 8 bytes from the file
                bytes.flip(); // Flip buffer before extracting bytes
                long exittime = bytes.getLong(); // Read bytes as a long
                // Figure out how long that time is from now and round
                // it to the nearest second.
                long secs = (exittime - System.currentTimeMillis() + 500) / 1000;
                // And tell the user about it.
                System.out.println("Try again in about " + secs + " seconds");
            } catch (IOException e) {
                // This probably means that locking is enforced by the OS
                // and we were prevented from reading the file.
            }

            // This is an abnormal exit, so set an exit code.
            System.exit(1);
        }

        // Simulate a real application by sleeping for 10 seconds.
        System.out.println("Starting...");
        Thread.sleep(10000);
        System.out.println("Exiting.");
    } finally {
        // Always release the lock and close the file
        // Closing the RandomAccessFile also closes its FileChannel.
        if (lock != null && lock.isValid())
            lock.release();
        if (file != null)
            file.close();
    }
}

From source file:Main.java

private static void writeFileFromBytes(final File file, final byte[] bytes) {
    FileChannel fc = null;
    try {//from   w w w .j  a  v a2s  .  c  o m
        fc = new FileOutputStream(file, false).getChannel();
        fc.write(ByteBuffer.wrap(bytes));
        fc.force(true);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fc != null) {
                fc.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:Main.java

public static void toFile(ByteBuffer buffer, File file) throws IOException {
    RandomAccessFile raf = null;//from   ww  w. ja  va 2 s. c o  m
    FileChannel channel = null;
    try {
        raf = new RandomAccessFile(file, "rw");
        channel = raf.getChannel();
        channel.write(buffer);
        channel.force(false /*metadata*/);
        channel.close();
        raf.close();
    } finally {
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException e) {
                // Ignored.
            }
        }
        if (raf != null) {
            try {
                raf.close();
            } catch (IOException e) {
                // Ignored.
            }
        }
    }
}

From source file:com.github.neoio.nio.util.NIOUtils.java

public static void resetFileChannelForReading(FileChannel channel) throws NetIOException {
    try {//  w  ww  . j a  va2 s.  com
        channel.force(true);
        channel.position(0);
    } catch (IOException e) {
        throw new NetIOException(e);
    }
}

From source file:cd.education.data.collector.android.utilities.FileUtils.java

private static String actualCopy(File sourceFile, File destFile) {
    FileInputStream fileInputStream = null;
    FileOutputStream fileOutputStream = null;
    FileChannel src = null;/*from   w  w w .  jav a 2  s .c o m*/
    FileChannel dst = null;
    try {
        fileInputStream = new FileInputStream(sourceFile);
        src = fileInputStream.getChannel();
        fileOutputStream = new FileOutputStream(destFile);
        dst = fileOutputStream.getChannel();
        dst.transferFrom(src, 0, src.size());
        dst.force(true);
        return null;
    } catch (FileNotFoundException e) {
        Log.e(t, "FileNotFoundException while copying file", e);
        return e.getMessage();
    } catch (IOException e) {
        Log.e(t, "IOException while copying file", e);
        return e.getMessage();
    } catch (Exception e) {
        Log.e(t, "Exception while copying file", e);
        return e.getMessage();
    } finally {
        IOUtils.closeQuietly(fileInputStream);
        IOUtils.closeQuietly(fileOutputStream);
        IOUtils.closeQuietly(src);
        IOUtils.closeQuietly(dst);
    }
}

From source file:Main.java

public static boolean fileCopy(File srcFile, File dstFile) {
    int length = 1048891;
    FileChannel inC = null;// w  w  w. j av  a 2  s.  c  om
    FileChannel outC = null;
    try {
        FileInputStream in = new FileInputStream(srcFile);
        FileOutputStream out = new FileOutputStream(dstFile);
        inC = in.getChannel();
        outC = out.getChannel();
        ByteBuffer b = null;
        while (inC.position() < inC.size()) {
            if ((inC.size() - inC.position()) < length) {
                length = (int) (inC.size() - inC.position());
            } else {
                length = 1048891;
            }
            b = ByteBuffer.allocateDirect(length);
            inC.read(b);
            b.flip();
            outC.write(b);
            outC.force(false);
        }

        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        try {
            if (inC != null && inC.isOpen()) {
                inC.close();
            }
            if (outC != null && outC.isOpen()) {
                outC.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.imaginea.kodebeagle.base.util.Utils.java

public void forceWrite(final String contents, final File file) throws IOException {
    try (FileOutputStream s = new FileOutputStream(file.getAbsolutePath(), false)) {
        s.write(contents.getBytes(StandardCharsets.UTF_8.name()));
        FileChannel c = s.getChannel();
        c.force(true);
        s.getFD().sync();/* ww  w . j  a v a2s .c  o  m*/
        c.close();
        s.close();
    }
}

From source file:edu.rit.flick.genetics.FastFileDeflator.java

@SuppressWarnings("resource")
protected void removeUnusedBufferSpace(final String tmpOutputDirectory)
        throws IOException, InterruptedException {
    final long actualDataHcfFileSize = datahcf.position();
    final long actualNFileSize = nfile.position();

    fastIn.close();//  w ww.j a  v a  2s . c om
    datahcf.close();
    headerfile.close();
    nfile.close();
    iupacfile.close();
    tailfile.close();
    metafile.close();

    fastIn = null;
    datahcf = null;
    nfile = null;

    // Give the last method a moment to garbage collect
    // System.gc();
    // Thread.sleep( 1000 );

    final File dataFile = new File(tmpOutputDirectory + SEQUENCE_DATA_FILE);
    final File nFile = new File(tmpOutputDirectory + N_FILE);

    // Remove unused buffer space
    FileChannel fc = new FileOutputStream(dataFile, true).getChannel();
    fc.force(true);
    fc.truncate(actualDataHcfFileSize).close();

    fc = new FileOutputStream(nFile, true).getChannel();
    fc.force(true);
    fc.truncate(actualNFileSize).close();
}

From source file:com.yobidrive.diskmap.needles.NeedleManager.java

public void close() {
    Enumeration<FileChannel> channels = channelMap.elements();
    while (channels.hasMoreElements()) {
        FileChannel fc = channels.nextElement();
        try {//from   w w  w . ja  va2s .  c om
            fc.force(true);
            fc.close();
        } catch (Throwable th) {
            logger.error("Error closing needle channel", th);
        }
    }
}

From source file:com.yobidrive.diskmap.needles.NeedleManager.java

public void syncAll() {
    Enumeration<FileChannel> channels = channelMap.elements();
    while (channels.hasMoreElements()) {
        FileChannel fc = channels.nextElement();
        try {//  w w  w . java 2s .c  o m
            fc.force(true);
        } catch (Throwable th) {
            logger.error("Error synching needle channel", th);
        }
    }
    // logger.info(needleHeaderReadCache.stats().toString()) ;
}