Getting Channels From Streams
From Java Example Source Code
Contents |
[edit] Overview - Getting Channels From Streams
This is a example of Java program.
[edit] Java Source Code
- Package: com.bruceeckel
- File: GetChannel.java
package com.bruceeckel; //: c12:GetChannel.java //Getting channels from streams //{Clean: data.txt} //From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002 //www.BruceEckel.com. See copyright notice in CopyRight.txt. import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class GetChannel { private static final int BSIZE = 1024; public static void main(String[] args) throws Exception { // Write a file: FileChannel fc = new FileOutputStream("data.txt").getChannel(); fc.write(ByteBuffer.wrap("Some text ".getBytes())); fc.close(); // Add to the end of the file: fc = new RandomAccessFile("data.txt", "rw").getChannel(); fc.position(fc.size()); // Move to the end fc.write(ByteBuffer.wrap("Some more".getBytes())); fc.close(); // Read the file: fc = new FileInputStream("data.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); fc.read(buff); buff.flip(); while (buff.hasRemaining()) System.out.print((char) buff.get()); } }
[edit] What Result You Can Get
Run the program, you will get:
Some text Some more
[edit] Required External Library for this Java Example
Need nothing.
[edit] How to Run this Java Example Program
We recommend running this Java example program with Eclipse.
For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.
It's fairly easy.
