Example usage for java.io FileOutputStream getChannel

List of usage examples for java.io FileOutputStream getChannel

Introduction

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

Prototype

public FileChannel getChannel() 

Source Link

Document

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

Usage

From source file:NIOCopy.java

public static void main(String args[]) throws Exception {
    FileInputStream fIn;//ww w. ja va  2s. c  o  m
    FileOutputStream fOut;
    FileChannel fIChan, fOChan;
    long fSize;
    MappedByteBuffer mBuf;

    fIn = new FileInputStream(args[0]);
    fOut = new FileOutputStream(args[1]);

    fIChan = fIn.getChannel();
    fOChan = fOut.getChannel();
    fSize = fIChan.size();

    mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize);
    fOChan.write(mBuf); // this copies the file
    fIChan.close();
    fIn.close();

    fOChan.close();
    fOut.close();
}

From source file:MainClass.java

public static void main(String[] args) {
    long[] primes = new long[] { 1, 2, 3, 5, 7 };
    File aFile = new File("C:/test/primes.txt");
    FileOutputStream outputFile = null;
    try {/*  w  w  w.  j a  va2 s  . co m*/
        outputFile = new FileOutputStream(aFile);
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
    }
    FileChannel file = outputFile.getChannel();
    final int BUFFERSIZE = 100;
    ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE);
    DoubleBuffer doubleBuf = buf.asDoubleBuffer();
    buf.position(8);
    CharBuffer charBuf = buf.asCharBuffer();
    for (long prime : primes) {
        String primeStr = "prime = " + prime;
        doubleBuf.put(0, (double) primeStr.length());
        charBuf.put(primeStr);
        buf.position(2 * charBuf.position() + 8);
        LongBuffer longBuf = buf.asLongBuffer();
        longBuf.put(prime);
        buf.position(buf.position() + 8);
        buf.flip();
        try {
            file.write(buf);
        } catch (IOException e) {
            e.printStackTrace(System.err);
        }
        buf.clear();
        doubleBuf.clear();
        charBuf.clear();
    }
    try {
        System.out.println("File written is " + file.size() + "bytes.");
        outputFile.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
}

From source file:MainClass.java

public static void main(String[] args) {
    String[] phrases = { "A", "B 1", "C 1.3" };
    String dirname = "C:/test";
    String filename = "Phrases.txt";
    File dir = new File(dirname);
    File aFile = new File(dir, filename);
    FileOutputStream outputFile = null;
    try {//  w  w w  . ja v a 2  s.c o  m
        outputFile = new FileOutputStream(aFile, true);
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
    }
    FileChannel outChannel = outputFile.getChannel();
    ByteBuffer buf = ByteBuffer.allocate(1024);
    System.out.println(buf.position());
    System.out.println(buf.limit());
    System.out.println(buf.capacity());
    CharBuffer charBuf = buf.asCharBuffer();
    System.out.println(charBuf.position());
    System.out.println(charBuf.limit());
    System.out.println(charBuf.capacity());
    Formatter formatter = new Formatter(charBuf);
    int number = 0;
    for (String phrase : phrases) {
        formatter.format("%n %s", ++number, phrase);
        System.out.println(charBuf.position());
        System.out.println(charBuf.limit());
        System.out.println(charBuf.capacity());
        charBuf.flip();
        System.out.println(charBuf.position());
        System.out.println(charBuf.limit());
        System.out.println(charBuf.length());
        buf.limit(2 * charBuf.length()); // Set byte buffer limit
        System.out.println(buf.position());
        System.out.println(buf.limit());
        System.out.println(buf.remaining());
        try {
            outChannel.write(buf);
            buf.clear();
            charBuf.clear();
        } catch (IOException e) {
            e.printStackTrace(System.err);
        }
    }
    try {
        outputFile.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
}

From source file:MainClass.java

public static void main(String args[]) {
    FileInputStream fIn;// ww w.j a v  a2 s . co  m
    FileOutputStream fOut;
    FileChannel fIChan, fOChan;
    long fSize;
    MappedByteBuffer mBuf;

    try {
        fIn = new FileInputStream(args[0]);
        fOut = new FileOutputStream(args[1]);

        fIChan = fIn.getChannel();
        fOChan = fOut.getChannel();

        fSize = fIChan.size();

        mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize);

        fOChan.write(mBuf); // this copies the file

        fIChan.close();
        fIn.close();

        fOChan.close();
        fOut.close();
    } catch (IOException exc) {
        System.out.println(exc);
        System.exit(1);
    } catch (ArrayIndexOutOfBoundsException exc) {
        System.out.println("Usage: Copy from to");
        System.exit(1);
    }
}

From source file:MainClass.java

public static void main(String[] args) {
    int count = 100;

    long[] numbers = new long[count];

    for (int i = 0; i < numbers.length; i++) {
        numbers[i] = i;//  w  w  w.j  av  a2s  .co m

    }
    File aFile = new File("data.bin");
    FileOutputStream outputFile = null;
    try {
        outputFile = new FileOutputStream(aFile);
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    }
    FileChannel file = outputFile.getChannel();
    final int BUFFERSIZE = 100;
    ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE);
    LongBuffer longBuf = buf.asLongBuffer();

    int numberWritten = 0;

    while (numberWritten < numbers.length) {
        longBuf.put(numbers, numberWritten, min(longBuf.capacity(), numbers.length - numberWritten));
        buf.limit(8 * longBuf.position());
        try {
            file.write(buf);
            numberWritten += longBuf.position();
        } catch (IOException e) {
            e.printStackTrace(System.err);
            System.exit(1);
        }
        longBuf.clear();
        buf.clear();
    }

    try {
        System.out.println("File written is " + file.size() + " bytes.");
        outputFile.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    }
}

From source file:MainClass.java

public static void main(String[] args) {
    String phrase = new String("text \n");
    String dirname = "C:/test";
    String filename = "charData.txt";
    File dir = new File(dirname);
    File aFile = new File(dir, filename);
    FileOutputStream outputFile = null;
    try {//from www.j a v  a2  s  .c o  m
        outputFile = new FileOutputStream(aFile, true);
        System.out.println("File stream created successfully.");
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
    }
    FileChannel outChannel = outputFile.getChannel();
    ByteBuffer buf = ByteBuffer.allocate(1024);
    System.out.println("New buffer:           position = " + buf.position() + "\tLimit = " + buf.limit()
            + "\tcapacity = " + buf.capacity());
    for (char ch : phrase.toCharArray()) {
        buf.putChar(ch);
    }
    System.out.println("Buffer after loading: position = " + buf.position() + "\tLimit = " + buf.limit()
            + "\tcapacity = " + buf.capacity());
    buf.flip();
    System.out.println("Buffer after flip:   position = " + buf.position() + "\tLimit = " + buf.limit()
            + "\tcapacity = " + buf.capacity());
    try {
        outChannel.write(buf);
        outputFile.close();
        System.out.println("Buffer contents written to file.");
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
}

From source file:MainClass.java

public static void main(String[] args) {
    String phrase = new String("www.java2s.com\n");

    File aFile = new File("test.txt");
    FileOutputStream outputFile = null;
    try {//www  . ja  va  2s  . c om
        outputFile = new FileOutputStream(aFile, true);
        System.out.println("File stream created successfully.");
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
    }

    FileChannel outChannel = outputFile.getChannel();

    ByteBuffer buf = ByteBuffer.allocate(1024);
    System.out.println("New buffer:           position = " + buf.position() + "\tLimit = " + buf.limit()
            + "\tcapacity = " + buf.capacity());

    // Load the data into the buffer
    for (char ch : phrase.toCharArray()) {
        buf.putChar(ch);
    }
    System.out.println("Buffer after loading: position = " + buf.position() + "\tLimit = " + buf.limit()
            + "\tcapacity = " + buf.capacity());
    buf.flip();
    System.out.println("Buffer after flip:    position = " + buf.position() + "\tLimit = " + buf.limit()
            + "\tcapacity = " + buf.capacity());

    try {
        outChannel.write(buf);
        outputFile.close();
        System.out.println("Buffer contents written to file.");
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
}

From source file:MainClass.java

public static void main(String[] a) {
    File aFile = new File("C:/myFile.text");
    FileOutputStream outputFile = null; // Place to store an output stream
                                        // reference
    try {/*from ww w .  j  a va  2 s.c  o  m*/
        // Create the stream opened to write
        outputFile = new FileOutputStream(aFile);
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    }
    // Get the channel for the file
    FileChannel outputChannel = outputFile.getChannel();
}

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;/*from   ww  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:org.commoncrawl.util.S3Downloader.java

public static void main(String[] args) {

    boolean isRequesterPays = args[3].equals("1");
    S3Downloader downloader = new S3Downloader(args[0], args[1], args[2], isRequesterPays);
    String itemToFetch = args[4];

    try {// w  w  w .java 2 s. c o m

        downloader.initialize(new Callback() {

            Map<String, FileChannel> channelMap = new HashMap<String, FileChannel>();

            public boolean contentAvailable(int itemId, String itemKey, NIOBufferList contentBuffer) {
                LOG.info("Key:" + itemKey + " GOT:" + contentBuffer.available() + " Bytes");

                FileChannel channel = channelMap.get(itemKey);
                if (channel != null) {
                    try {
                        while (contentBuffer.available() != 0) {
                            ByteBuffer buffer = contentBuffer.read();
                            channel.write(buffer);
                        }
                        return true;
                    } catch (IOException e) {
                        LOG.error(StringUtils.stringifyException(e));
                        return false;
                    }
                }
                return false;
            }

            public void downloadComplete(int itemId, String itemKey) {
                LOG.info("Key:" + itemKey + " DownloadComplete");
                FileChannel channel = channelMap.get(itemKey);
                if (channel != null) {
                    try {
                        channel.close();
                    } catch (IOException e) {
                        LOG.error(StringUtils.stringifyException(e));
                    }
                }
                channelMap.remove(itemKey);
            }

            public void downloadFailed(int itemId, String itemKey, String errorCode) {
                LOG.info("Key:" + itemKey + " DownloadFailed. ErrorCode:" + errorCode);
                FileChannel channel = channelMap.get(itemKey);
                if (channel != null) {
                    try {
                        channel.close();
                    } catch (IOException e) {
                        LOG.error(StringUtils.stringifyException(e));
                    }
                }
                channelMap.remove(itemKey);
            }

            public boolean downloadStarting(int itemId, String itemKey, int contentLength) {
                LOG.info("Key:" + itemKey + " DownloadStarting - ContentLength:" + contentLength);
                File file = new File("/tmp/" + itemKey);
                if (file.exists())
                    file.delete();
                file.getParentFile().mkdirs();
                FileOutputStream fileHandle = null;
                try {
                    fileHandle = new FileOutputStream(file);
                    //LOG.info("Key:" + itemKey + " Created File:" + file.getAbsolutePath());
                    channelMap.put(itemKey, fileHandle.getChannel());
                } catch (IOException e) {
                    LOG.error(StringUtils.stringifyException(e));
                    if (fileHandle != null)
                        try {
                            fileHandle.close();
                        } catch (IOException e1) {
                        }
                    return false;
                }

                return true;
            }
        });

        downloader.fetchItem(itemToFetch);

        downloader.waitForCompletion();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}