Example usage for java.io RandomAccessFile getChannel

List of usage examples for java.io RandomAccessFile getChannel

Introduction

In this page you can find the example usage for java.io RandomAccessFile getChannel.

Prototype

public final FileChannel getChannel() 

Source Link

Document

Returns the unique java.nio.channels.FileChannel FileChannel object associated with this file.

Usage

From source file:MainClass.java

public static void main(String args[]) {
    RandomAccessFile randomAccessFile;
    FileChannel fileChannel;//w ww .j a va 2 s  .  c o m
    ByteBuffer byteBuffer;

    try {
        randomAccessFile = new RandomAccessFile("test.txt", "rw");
        fileChannel = randomAccessFile.getChannel();
        byteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, 26);
        for (int i = 0; i < 10; i++)
            byteBuffer.put((byte) ('A' + i));
        fileChannel.close();
        randomAccessFile.close();
    } catch (IOException exc) {
        System.out.println(exc);
        System.exit(1);
    }
}

From source file:Main.java

public static void main(String[] args) {
    try {//from   w w w  . j ava2 s  .com
        RandomAccessFile raf = new RandomAccessFile("c:/test.txt", "rw");

        raf.writeUTF("java2s.com Hello World");

        // set the file pointer at 0 position
        raf.seek(0);

        // read and print the contents of the file
        System.out.println(raf.readUTF());

        // return the channel of the file
        System.out.println(raf.getChannel());

        // close the strea and release resources
        raf.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:VASSAL.launch.ModuleManager.java

public static void main(String[] args) {
    // FIXME: We need to catch more exceptions in main() and then exit in
    // order to avoid situations where the main thread ends due to an uncaught
    // exception, but there are other threads still running, and so VASSAL
    // does not quit. For example, this can happen if an IllegalArgumentException
    // is thrown here...

    // parse command-line arguments
    LaunchRequest lr = null;// w w w  .  jav  a  2  s .c o  m
    try {
        lr = LaunchRequest.parseArgs(args);
    } catch (LaunchRequestException e) {
        // FIXME: should be a dialog...
        System.err.println("VASSAL: " + e.getMessage());
        System.exit(1);
    }

    // do this before the graphics subsystem fires up or it won't stick
    System.setProperty("swing.boldMetal", "false");

    if (lr.mode == LaunchRequest.Mode.TRANSLATE) {
        // show the translation window in translation mode
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // FIXME: does this window exit on close?
                new TranslateVassalWindow(null).setVisible(true);
            }
        });
        return;
    }

    //
    // How we start exactly one request server:
    //
    // To ensure that exactly one process acts as the request server, we
    // acquire a lock on the ~/VASSAL/key file, and then attempt to acquire
    // a lock on the ~/VASSAL/lock file. If we cannot lock ~/VASSAL/lock,
    // then there is already a server running; in that case, we read the
    // port number and security key from ~/VASSAL/key. If we can lock
    // ~/VASSAL/lock, then we start the server, write the port number and
    // key to ~/VASSAL/key, and continue to hold the lock on ~/VASSAL/lock.
    // Finally, we unlock ~/VASSAL/key and proceed to act as a client,
    // sending requests over localhost:port using the security key.
    //
    // The advantages of this method are:
    //
    // (1) No race conditions between processes started at the same time.
    // (2) No port collisions, because we don't use a predetermined port.
    //

    final File keyfile = new File(Info.getConfDir(), "key");
    final File lockfile = new File(Info.getConfDir(), "lock");

    int port = 0;
    long key = 0;

    RandomAccessFile kraf = null;
    FileLock klock = null;
    try {
        // acquire an exclusive lock on the key file
        kraf = new RandomAccessFile(keyfile, "rw");

        try {
            klock = kraf.getChannel().lock();
        } catch (OverlappingFileLockException e) {
            throw (IOException) new IOException().initCause(e);
        }

        // determine whether we are the server or a client

        // Note: We purposely keep lout open in the case where we are the
        // server, because closing lout will release the lock.
        FileLock lock = null;
        final FileOutputStream lout = new FileOutputStream(lockfile);
        try {
            lock = lout.getChannel().tryLock();
        } catch (OverlappingFileLockException e) {
            throw (IOException) new IOException().initCause(e);
        }

        if (lock != null) {
            // we have the lock, so we will be the request server

            // bind to an available port on the loopback device
            final ServerSocket serverSocket = new ServerSocket(0, 0, InetAddress.getByName(null));

            // write the port number where we listen to the key file
            port = serverSocket.getLocalPort();
            kraf.writeInt(port);

            // create new security key and write it to the key file
            key = (long) (Math.random() * Long.MAX_VALUE);
            kraf.writeLong(key);

            // create a new Module Manager
            new ModuleManager(serverSocket, key, lout, lock);
        } else {
            // we do not have the lock, so we will be a request client
            lout.close();

            // read the port number we will connect to from the key file
            port = kraf.readInt();

            // read the security key from the key file
            key = kraf.readLong();
        }

        kraf.close();
    } catch (IOException e) {
        // FIXME: should be a dialog...
        System.err.println("VASSAL: IO error");
        e.printStackTrace();
        System.exit(1);
    } finally {
        // this will also release the lock on the key file
        IOUtils.closeQuietly(kraf);
    }

    lr.key = key;

    // pass launch parameters on to the ModuleManager via the socket
    Socket clientSocket = null;
    ObjectOutputStream out = null;
    InputStream in = null;
    try {
        clientSocket = new Socket((String) null, port);

        out = new ObjectOutputStream(new BufferedOutputStream(clientSocket.getOutputStream()));
        out.writeObject(lr);
        out.flush();

        in = clientSocket.getInputStream();
        IOUtils.copy(in, System.err);
    } catch (IOException e) {
        // FIXME: should be a dialog...
        System.err.println("VASSAL: Problem with socket on port " + port);
        e.printStackTrace();
        System.exit(1);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly((Closeable) out);
        IOUtils.closeQuietly(clientSocket);
    }
}

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();

        // 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();//from w  ww . j  a  v  a 2s  .  c  om

        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:es.cnio.bioinfo.bicycle.gatk.MethylationFilePair.java

public static void main(String[] args) throws IOException {
    File f = new File("/mnt/lacie15t/BACKUP/lipido/NGS/LISTER/REFERENCES/phageLambda_plus_hg18.fa.fai");
    RandomAccessFile ra = new RandomAccessFile(f, "rw");
    ra.getChannel().lock(0, Long.MAX_VALUE, false);

    //a//from   w  w w.  j  a  v a 2  s.  com
    /*   ra.seek(0);
       ra.write("hello2\n".getBytes());   
       ra.close();
       */
    //b
    FileOutputStream fos = new FileOutputStream(f);
    fos.write("hello\n".getBytes());
    fos.close();

}

From source file:Main.java

public static long truncateFile(String fileName, long size) throws FileNotFoundException, IOException {
    RandomAccessFile raf = new RandomAccessFile(fileName, "rw");

    if (raf.length() >= size) {
        FileChannel channel = raf.getChannel();
        channel.truncate(size);//from w w  w.  j  a va  2 s .  c o m
        return size;
    }

    return raf.length();
}

From source file:com.cloudhopper.commons.io.demo.FileServerMain.java

public static void loadFilesFromDir(String dir, int threads) {
    ThreadPoolExecutor ex = new ThreadPoolExecutor(threads, threads, 5000l, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>());
    ex.prestartAllCoreThreads();/* w  w  w  . j av  a 2s  .  c  o  m*/

    IdGenerator idGen = new UUIDIdGenerator();
    final FileStore store = new SimpleNIOFileStore(idGen, "/tmp/fileStore/");

    final long start = System.currentTimeMillis();
    int count = 0;

    Iterator<File> it = FileUtils.iterateFiles(new File(dir), null, true);
    while (it.hasNext()) {
        final File f = it.next();
        final int num = count++;
        Runnable job = new Runnable() {

            @Override
            public void run() {
                try {
                    RandomAccessFile randomAccessFile = new RandomAccessFile(f, "r");
                    FileChannel fileChannel = randomAccessFile.getChannel();
                    Id id = store.write(fileChannel);
                    System.out.println("(" + num + ") Stored " + f.getPath() + " as " + id.getName() + " after "
                            + (System.currentTimeMillis() - start) + "ms");
                } catch (Exception e) {
                    logger.error("", e);
                }
            }
        };
        ex.execute(job);
    }
}

From source file:Main.java

public static ByteBuffer fromFile(File file) throws IOException {
    RandomAccessFile raf = null;
    FileChannel channel = null;/*from  ww  w  . j ava2 s.  c  o m*/
    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 toFile(ByteBuffer buffer, File file) throws IOException {
    RandomAccessFile raf = null;
    FileChannel channel = null;/*from www.  ja va2s.c  o  m*/
    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:eu.mhutti1.utils.storage.StorageDeviceUtils.java

private static boolean canWrite(File file) {
    try {//www. ja v a2 s  .  c om
        RandomAccessFile randomAccessFile = new RandomAccessFile(file + "/test.txt", "rw");
        FileChannel fileChannel = randomAccessFile.getChannel();
        FileLock fileLock = fileChannel.lock();
        fileLock.release();
        fileChannel.close();
        randomAccessFile.close();
        return true;
    } catch (Exception ex) {
        return false;
    }
}