Java/File Input Output/FileChannel

Материал из Java эксперт
Перейти к: навигация, поиск

A character output stream that sends output to a printer

 
/*
 * Copyright (c) 2004 David Flanagan.  All rights reserved.
 * This code is from the book Java Examples in a Nutshell, 3nd Edition.
 * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
 * You may study, use, and modify it for any non-commercial purpose,
 * including teaching and use in open-source projects.
 * You may distribute it non-commercially as long as you retain this notice.
 * For a commercial use license, or to purchase the book, 
 * please visit http://www.davidflanagan.ru/javaexamples3.
 */
//package je3.print;
import java.awt.Button;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Panel;
import java.awt.PrintJob;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileReader;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.DateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.TimeZone;
/**
 * A character output stream that sends output to a printer.
 */
public class HardcopyWriter extends Writer {
  // These are the instance variables for the class
  protected PrintJob job; // The PrintJob object in use
  protected Graphics page; // Graphics object for current page
  protected String jobname; // The name of the print job
  protected int fontsize; // Point size of the font
  protected String time; // Current time (appears in header)
  protected Dimension pagesize; // Size of the page (in dots)
  protected int pagedpi; // Page resolution in dots per inch
  protected Font font, headerfont; // Body font and header font
  protected FontMetrics metrics; // Metrics for the body font
  protected FontMetrics headermetrics; // Metrics for the header font
  protected int x0, y0; // Upper-left corner inside margin
  protected int width, height; // Size (in dots) inside margins
  protected int headery; // Baseline of the page header
  protected int charwidth; // The width of each character
  protected int lineheight; // The height of each line
  protected int lineascent; // Offset of font baseline
  protected int chars_per_line; // Number of characters per line
  protected int lines_per_page; // Number of lines per page
  protected int charnum = 0, linenum = 0; // Current column and line position
  protected int pagenum = 0; // Current page number
  // A field to save state between invocations of the write() method
  private boolean last_char_was_return = false;
  // A static variable that holds user preferences between print jobs
  protected static Properties printprops = new Properties();
  /**
   * The constructor for this class has a bunch of arguments: The frame argument
   * is required for all printing in Java. The jobname appears left justified at
   * the top of each printed page. The font size is specified in points, as
   * on-screen font sizes are. The margins are specified in inches (or fractions
   * of inches).
   */
  public HardcopyWriter(Frame frame, String jobname, int fontsize, double leftmargin,
      double rightmargin, double topmargin, double bottommargin)
      throws HardcopyWriter.PrintCanceledException {
    // Get the PrintJob object with which we"ll do all the printing.
    // The call is synchronized on the static printprops object, which
    // means that only one print dialog can be popped up at a time.
    // If the user clicks Cancel in the print dialog, throw an exception.
    Toolkit toolkit = frame.getToolkit(); // get Toolkit from Frame
    synchronized (printprops) {
      job = toolkit.getPrintJob(frame, jobname, printprops);
    }
    if (job == null)
      throw new PrintCanceledException("User cancelled print request");
    pagesize = job.getPageDimension(); // query the page size
    pagedpi = job.getPageResolution(); // query the page resolution
    // Bug Workaround:
    // On windows, getPageDimension() and getPageResolution don"t work, so
    // we"ve got to fake them.
    if (System.getProperty("os.name").regionMatches(true, 0, "windows", 0, 7)) {
      // Use screen dpi, which is what the PrintJob tries to emulate
      pagedpi = toolkit.getScreenResolution();
      // Assume a 8.5" x 11" page size. A4 paper users must change this.
      pagesize = new Dimension((int) (8.5 * pagedpi), 11 * pagedpi);
      // We also have to adjust the fontsize. It is specified in points,
      // (1 point = 1/72 of an inch) but Windows measures it in pixels.
      fontsize = fontsize * pagedpi / 72;
    }
    // Compute coordinates of the upper-left corner of the page.
    // I.e. the coordinates of (leftmargin, topmargin). Also compute
    // the width and height inside of the margins.
    x0 = (int) (leftmargin * pagedpi);
    y0 = (int) (topmargin * pagedpi);
    width = pagesize.width - (int) ((leftmargin + rightmargin) * pagedpi);
    height = pagesize.height - (int) ((topmargin + bottommargin) * pagedpi);
    // Get body font and font size
    font = new Font("Monospaced", Font.PLAIN, fontsize);
    metrics = frame.getFontMetrics(font);
    lineheight = metrics.getHeight();
    lineascent = metrics.getAscent();
    charwidth = metrics.charWidth("0"); // Assumes a monospaced font!
    // Now compute columns and lines will fit inside the margins
    chars_per_line = width / charwidth;
    lines_per_page = height / lineheight;
    // Get header font information
    // And compute baseline of page header: 1/8" above the top margin
    headerfont = new Font("SansSerif", Font.ITALIC, fontsize);
    headermetrics = frame.getFontMetrics(headerfont);
    headery = y0 - (int) (0.125 * pagedpi) - headermetrics.getHeight() + headermetrics.getAscent();
    // Compute the date/time string to display in the page header
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT);
    df.setTimeZone(TimeZone.getDefault());
    time = df.format(new Date());
    this.jobname = jobname; // save name
    this.fontsize = fontsize; // save font size
  }
  /**
   * This is the write() method of the stream. All Writer subclasses implement
   * this. All other versions of write() are variants of this one
   */
  public void write(char[] buffer, int index, int len) {
    synchronized (this.lock) { // For thread safety
      // Loop through all the characters passed to us
      for (int i = index; i < index + len; i++) {
        // If we haven"t begun a page (or a new page), do that now.
        if (page == null)
          newpage();
        // If the character is a line terminator, then begin new line,
        // unless it is a \n immediately after a \r.
        if (buffer[i] == "\n") {
          if (!last_char_was_return)
            newline();
          continue;
        }
        if (buffer[i] == "\r") {
          newline();
          last_char_was_return = true;
          continue;
        } else
          last_char_was_return = false;
        // If it some other non-printing character, ignore it.
        if (Character.isWhitespace(buffer[i]) && !Character.isSpaceChar(buffer[i])
            && (buffer[i] != "\t"))
          continue;
        // If no more characters will fit on the line, start new line.
        if (charnum >= chars_per_line) {
          newline();
          // Also start a new page, if necessary
          if (page == null)
            newpage();
        }
        // Now print the character:
        // If it is a space, skip one space, without output.
        // If it is a tab, skip the necessary number of spaces.
        // Otherwise, print the character.
        // It is inefficient to draw only one character at a time, but
        // because our FontMetrics don"t match up exactly to what the
        // printer uses we need to position each character individually
        if (Character.isSpaceChar(buffer[i]))
          charnum++;
        else if (buffer[i] == "\t")
          charnum += 8 - (charnum % 8);
        else {
          page.drawChars(buffer, i, 1, x0 + charnum * charwidth, y0 + (linenum * lineheight)
              + lineascent);
          charnum++;
        }
      }
    }
  }
  /**
   * This is the flush() method that all Writer subclasses must implement. There
   * is no way to flush a PrintJob without prematurely printing the page, so we
   * don"t do anything.
   */
  public void flush() { /* do nothing */
  }
  /**
   * This is the close() method that all Writer subclasses must implement. Print
   * the pending page (if any) and terminate the PrintJob.
   */
  public void close() {
    synchronized (this.lock) {
      if (page != null)
        page.dispose(); // Send page to the printer
      job.end(); // Terminate the job
    }
  }
  /**
   * Set the font style. The argument should be one of the font style constants
   * defined by the java.awt.Font class. All subsequent output will be in that
   * style. This method relies on all styles of the Monospaced font having the
   * same metrics.
   */
  public void setFontStyle(int style) {
    synchronized (this.lock) {
      // Try to set a new font, but restore current one if it fails
      Font current = font;
      try {
        font = new Font("Monospaced", style, fontsize);
      } catch (Exception e) {
        font = current;
      }
      // If a page is pending, set the new font. Otherwise newpage() will
      if (page != null)
        page.setFont(font);
    }
  }
  /** End the current page. Subsequent output will be on a new page. */
  public void pageBreak() {
    synchronized (this.lock) {
      newpage();
    }
  }
  /** Return the number of columns of characters that fit on the page */
  public int getCharactersPerLine() {
    return this.chars_per_line;
  }
  /** Return the number of lines that fit on a page */
  public int getLinesPerPage() {
    return this.lines_per_page;
  }
  /** This internal method begins a new line */
  protected void newline() {
    charnum = 0; // Reset character number to 0
    linenum++; // Increment line number
    if (linenum >= lines_per_page) { // If we"ve reached the end of page
      page.dispose(); // send page to printer
      page = null; // but don"t start a new page yet.
    }
  }
  /** This internal method begins a new page and prints the header. */
  protected void newpage() {
    page = job.getGraphics(); // Begin the new page
    linenum = 0;
    charnum = 0; // Reset line and char number
    pagenum++; // Increment page number
    page.setFont(headerfont); // Set the header font.
    page.drawString(jobname, x0, headery); // Print job name left justified
    String s = "- " + pagenum + " -"; // Print the page # centered.
    int w = headermetrics.stringWidth(s);
    page.drawString(s, x0 + (this.width - w) / 2, headery);
    w = headermetrics.stringWidth(time); // Print date right justified
    page.drawString(time, x0 + width - w, headery);
    // Draw a line beneath the header
    int y = headery + headermetrics.getDescent() + 1;
    page.drawLine(x0, y, x0 + width, y);
    // Set the basic monospaced font for the rest of the page.
    page.setFont(font);
  }
  /**
   * This is the exception class that the HardcopyWriter constructor throws when
   * the user clicks "Cancel" in the print dialog box.
   */
  public static class PrintCanceledException extends Exception {
    public PrintCanceledException(String msg) {
      super(msg);
    }
  }
  /**
   * A program that prints the specified file using HardcopyWriter
   */
  public static class PrintFile {
    public static void main(String[] args) {
      try {
        if (args.length != 1)
          throw new IllegalArgumentException("Wrong # of arguments");
        FileReader in = new FileReader(args[0]);
        HardcopyWriter out = null;
        Frame f = new Frame("PrintFile: " + args[0]);
        f.setSize(200, 50);
        f.show();
        try {
          out = new HardcopyWriter(f, args[0], 10, .5, .5, .5, .5);
        } catch (HardcopyWriter.PrintCanceledException e) {
          System.exit(0);
        }
        f.setVisible(false);
        char[] buffer = new char[4096];
        int numchars;
        while ((numchars = in.read(buffer)) != -1)
          out.write(buffer, 0, numchars);
        in.close();
        out.close();
      } catch (Exception e) {
        System.err.println(e);
        System.err.println("Usage: " + "java HardcopyWriter$PrintFile <filename>");
        System.exit(1);
      }
      System.exit(0);
    }
  }
  /**
   * A program that prints a demo page using HardcopyWriter
   */
  public static class Demo extends Frame implements ActionListener {
    /** The main method of the program. Create a test window */
    public static void main(String[] args) {
      Frame f = new Demo();
      f.show();
    }
    // Buttons used in this program
    protected Button print, quit;
    /** Constructor for the test program"s window. */
    public Demo() {
      super("HardcopyWriter Test"); // Call frame constructor
      Panel p = new Panel(); // Add a panel to the frame
      this.add(p, "Center"); // Center it
      p.setFont(new Font("SansSerif", // Set a default font
          Font.BOLD, 18));
      print = new Button("Print Test Page"); // Create a Print button
      quit = new Button("Quit"); // Create a Quit button
      print.addActionListener(this); // Specify that we"ll handle
      quit.addActionListener(this); // button presses
      p.add(print); // Add the buttons to panel
      p.add(quit);
      this.pack(); // Set the frame size
    }
    /** Handle the button presses */
    public void actionPerformed(ActionEvent e) {
      Object o = e.getSource();
      if (o == quit)
        System.exit(0);
      else if (o == print)
        printDemoPage();
    }
    /** Print the demo page */
    public void printDemoPage() {
      // Create a HardcopyWriter, using a 10 point font and 3/4" margins.
      HardcopyWriter hw;
      try {
        hw = new HardcopyWriter(this, "Demo Page", 10, .75, .75, .75, .75);
      } catch (HardcopyWriter.PrintCanceledException e) {
        return;
      }
      // Send output to it through a PrintWriter stream
      PrintWriter out = new PrintWriter(hw);
      // Figure out the size of the page
      int rows = hw.getLinesPerPage(), cols = hw.getCharactersPerLine();
      // Mark upper left and upper-right corners
      out.print("+"); // upper-left corner
      for (int i = 0; i < cols - 2; i++)
        out.print(" "); // space over
      out.print("+"); // upper-right corner
      // Display a title
      hw.setFontStyle(Font.BOLD + Font.ITALIC);
      out.println("\n\t\tHardcopy Writer Demo Page\n\n");
      // Demonstrate font styles
      hw.setFontStyle(Font.BOLD);
      out.println("Font Styles:");
      int[] styles = { Font.PLAIN, Font.BOLD, Font.ITALIC, Font.ITALIC + Font.BOLD };
      for (int i = 0; i < styles.length; i++) {
        hw.setFontStyle(styles[i]);
        out.println("ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz");
        out.println("1234567890!@#$%^&*()[]{}<>,.?:;+-=/\\`"\"_~|");
      }
      hw.setFontStyle(Font.PLAIN);
      out.println("\n");
      // Demonstrate tab stops
      hw.setFontStyle(Font.BOLD);
      out.println("Tab Stops:");
      hw.setFontStyle(Font.PLAIN);
      out.println("          1         2         3         4         5");
      out.println("012345678901234567890123456789012345678901234567890");
      out.println("^\t^\t^\t^\t^\t^\t^");
      out.println("\n");
      // Output some information about page dimensions and resolution
      hw.setFontStyle(Font.BOLD);
      out.println("Dimensions:");
      hw.setFontStyle(Font.PLAIN);
      out.println("\tResolution: " + hw.pagedpi + " dots per inch");
      out.println("\tPage width (pixels): " + hw.pagesize.width);
      out.println("\tPage height (pixels): " + hw.pagesize.height);
      out.println("\tWidth inside margins (pixels): " + hw.width);
      out.println("\tHeight inside margins (pixels): " + hw.height);
      out.println("\tCharacters per line: " + cols);
      out.println("\tLines per page: " + rows);
      // Skip down to the bottom of the page
      for (int i = 0; i < rows - 30; i++)
        out.println();
      // And mark the lower left and lower right
      out.print("+"); // lower-left
      for (int i = 0; i < cols - 2; i++)
        out.print(" "); // space-over
      out.print("+"); // lower-right
      // Close the output stream, forcing the page to be printed
      out.close();
    }
  }
}





Create an inputstream on the channel

 
import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a read/writeable file channel
    File file = new File("filename");
    FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
    InputStream is = Channels.newInputStream(channel);
    // Close the channel
    is.close();
  }
}





Create a private (copy-on-write) memory-mapped file.

 
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class Main {
  public static void main(String[] argv) throws Exception {
    File file = new File("filename");
    FileChannel roChannel = new RandomAccessFile(file, "r").getChannel();
    ByteBuffer readonlybuffer = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, (int) roChannel
        .size());
    FileChannel rwChannel = new RandomAccessFile(file, "rw").getChannel();
    ByteBuffer writeonlybuffer = rwChannel.map(FileChannel.MapMode.READ_WRITE, 0, (int) rwChannel
        .size());
    // Create a private (copy-on-write) memory-mapped file.
    FileChannel pvChannel = new RandomAccessFile(file, "rw").getChannel();
    ByteBuffer privatebuffer = roChannel.map(FileChannel.MapMode.READ_WRITE, 0, (int) rwChannel
        .size());
  }
}





Create a read-only memory-mapped file

 
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class Main {
  public static void main(String[] argv) throws Exception {
    File file = new File("filename");
    // Create a read-only memory-mapped file
    FileChannel roChannel = new RandomAccessFile(file, "r").getChannel();
    ByteBuffer readonlybuffer = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, (int) roChannel
        .size());

  }
}





Create a read-write memory-mapped file

 
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class Main {
  public static void main(String[] argv) throws Exception {
    File file = new File("filename");
//  Create a read-write memory-mapped file
    FileChannel rwChannel = new RandomAccessFile(file, "rw").getChannel();
    ByteBuffer writeonlybuffer = rwChannel.map(FileChannel.MapMode.READ_WRITE, 0, (int) rwChannel
        .size());

  }
}





Creating a Stream from a Channel

 
import java.io.File;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a read/writeable file channel
    File file = new File("filename");
    FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
    OutputStream os = Channels.newOutputStream(channel);
    os.close();
  }
}





Demonstrates file locking and simple file read and write operations using java.nio.channels.FileChannel

 
 
/*
 * Copyright (c) 2004 David Flanagan.  All rights reserved.
 * This code is from the book Java Examples in a Nutshell, 3nd Edition.
 * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
 * You may study, use, and modify it for any non-commercial purpose,
 * including teaching and use in open-source projects.
 * You may distribute it non-commercially as long as you retain this notice.
 * For a commercial use license, or to purchase the book, 
 * please visit http://www.davidflanagan.ru/javaexamples3.
 */
//package je3.nio;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
/**
 * Lock.java: this class demonstrates file locking and simple file read and
 * write operations using java.nio.channels.FileChannel. It uses file locking to
 * prevent two instances of the program from running at the same time.
 */
public class Lock {
  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();
      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();
    }
  }
}





Get FileChannel from FileOutputStream and FileInputStream

 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class CopyChannels {
  public static void main(String[] args) throws Exception {
    String fromFileName = "from.txt";
    String toFileName = "to.txt";
    FileChannel in = new FileInputStream(fromFileName).getChannel();
    FileChannel out = new FileOutputStream(toFileName).getChannel();
    ByteBuffer buff = ByteBuffer.allocate(32 * 1024);
    while (in.read(buff) > 0) {
      buff.flip();
      out.write(buff);
      buff.clear();
    }
    in.close();
    out.close();
  }
}





Performs a straightforward copy operation

  
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
public class Copy {
  public static void main(String[] args) {
    FileChannel in = null;
    FileChannel out = null;
    if (args.length < 2) {
      System.out.println("Usage: java Copy <from> <to>");
      System.exit(1);
    }
    try {
      in = new FileInputStream(args[0]).getChannel();
      out = new FileOutputStream(args[1]).getChannel();
      out.transferFrom(in, 0L, (int) in.size());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}





Read bytes from the specified channel, decode them using the specified Charset, and write the resulting characters to the specified writer

 
   
/*
 * Copyright (c) 2004 David Flanagan.  All rights reserved.
 * This code is from the book Java Examples in a Nutshell, 3nd Edition.
 * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
 * You may study, use, and modify it for any non-commercial purpose,
 * including teaching and use in open-source projects.
 * You may distribute it non-commercially as long as you retain this notice.
 * For a commercial use license, or to purchase the book, 
 * please visit http://www.davidflanagan.ru/javaexamples3.
 */
//package je3.nio;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
public class ChannelToWriter {
  /**
   * Read bytes from the specified channel, decode them using the specified
   * Charset, and write the resulting characters to the specified writer
   */
  public static void copy(ReadableByteChannel channel, Writer writer, Charset charset)
      throws IOException {
    // Get and configure the CharsetDecoder we"ll use
    CharsetDecoder decoder = charset.newDecoder();
    decoder.onMalformedInput(CodingErrorAction.IGNORE);
    decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
    // Get the buffers we"ll use, and the backing array for the CharBuffer.
    ByteBuffer bytes = ByteBuffer.allocateDirect(2 * 1024);
    CharBuffer chars = CharBuffer.allocate(2 * 1024);
    char[] array = chars.array();
    while (channel.read(bytes) != -1) { // Read from channel until EOF
      bytes.flip(); // Switch to drain mode for decoding
      // Decode the byte buffer into the char buffer.
      // Pass false to indicate that we"re not done.
      decoder.decode(bytes, chars, false);
      // Put the char buffer into drain mode, and write its contents
      // to the Writer, reading them from the backing array.
      chars.flip();
      writer.write(array, chars.position(), chars.remaining());
      // Discard all bytes we decoded, and put the byte buffer back into
      // fill mode. Since all characters were output, clear that buffer.
      bytes.rupact(); // Discard decoded bytes
      chars.clear(); // Clear the character buffer
    }
    // At this point there may still be some bytes in the buffer to decode
    // So put the buffer into drain mode call decode() a final time, and
    // finish with a flush().
    bytes.flip();
    decoder.decode(bytes, chars, true); // True means final call
    decoder.flush(chars); // Flush any buffered chars
    // Write these final chars (if any) to the writer.
    chars.flip();
    writer.write(array, chars.position(), chars.remaining());
    writer.flush();
  }
  // A test method: copy a UTF-8 file to standard out
  public static void main(String[] args) throws IOException {
    FileChannel c = new FileInputStream(args[0]).getChannel();
    OutputStreamWriter w = new OutputStreamWriter(System.out);
    Charset utf8 = Charset.forName("UTF-8");
    ChannelToWriter.copy(c, w, utf8);
    c.close();
    w.close();
  }
}





Transfer between FileChannel

 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
public class Main {
  public static void main(String[] args) throws Exception {
    String fromFileName = "from.txt";
    String toFileName = "to.txt";
    FileChannel in = new FileInputStream(fromFileName).getChannel();
    FileChannel out = new FileOutputStream(toFileName).getChannel();
    in.transferTo(0, (int) in.size(), out);
    in.close();
    out.close();
  }
}





Using FileChannels to Access a File

 
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class Main {
  public static void main(String args[]) throws IOException {
    FileInputStream fis = new FileInputStream("FileChannelExample.java");
    FileChannel fc = fis.getChannel();
    ByteBuffer bb = ByteBuffer.allocate((int) fc.size());
    fc.read(bb);
    bb.flip();
    String fileContent = new String(bb.array());
    fc.close();
    fc = null;
    System.out.println("fileContent = " + fileContent);
  }
}





Write to a file using FileChannel.

  
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ExplicitChannelWrite {
  public static void main(String args[]) {
    FileOutputStream fOut;
    FileChannel fChan;
    ByteBuffer mBuf;
    try {
      fOut = new FileOutputStream("test.txt");
      fChan = fOut.getChannel();
      mBuf = ByteBuffer.allocateDirect(26);
      for (int i = 0; i < 26; i++)
        mBuf.put((byte) ("A" + i));
      mBuf.rewind();
      fChan.write(mBuf);
      fChan.close();
      fOut.close();
    } catch (IOException exc) {
      System.out.println(exc);
      System.exit(1);
    }
  }
}