Java FileChannel read text file

Description

Java FileChannel read text 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[]) {
      FileInputStream fIn = null;
      FileChannel fChan = null;//from  w  w w  .ja  v  a 2  s  . co m
      ByteBuffer mBuf;
      int count;

      try {
         // First, open a file for input.
         fIn = new FileInputStream("test.txt");

         // Next, obtain a channel to that file.
         fChan = fIn.getChannel();

         // Allocate a buffer.
         mBuf = ByteBuffer.allocate(128);

         do {
            count = fChan.read(mBuf);

            if (count != -1) {

               mBuf.rewind();

               for (int i = 0; i < count; i++)
                  System.out.print((char) mBuf.get());
            }
         } while (count != -1);

         System.out.println();

      } catch (IOException e) {
         System.out.println("I/O Error " + e);
      } finally {
         try {
            if (fChan != null)
               fChan.close(); // close channel
         } catch (IOException e) {
            System.out.println("Error Closing Channel.");
         }
         try {
            if (fIn != null)
               fIn.close(); // close file
         } catch (IOException e) {
            System.out.println("Error Closing 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[]) {
      FileInputStream fIn;//w  w w.  j ava2s.co m
      FileChannel fChan;
      long fSize;
      ByteBuffer mBuf;

      try {
         fIn = new FileInputStream("Main.java");
         fChan = fIn.getChannel();
         fSize = fChan.size();
         mBuf = ByteBuffer.allocate((int) fSize);
         fChan.read(mBuf);
         mBuf.rewind();
         for (int i = 0; i < fSize; i++)
            System.out.print((char) mBuf.get());
         fChan.close();
         fIn.close();
      } catch (IOException exc) {
         System.out.println(exc);
         System.exit(1);
      }
   }
}



PreviousNext

Related