Reading/Writing To/From Files Using Filechannel Together With Bytebuffer Inwards Java

Reading/Writing To/From Files Using Filechannel Together With Bytebuffer Inwards Java - Hallo sahabat BEST LEARNING JAVA, Pada Artikel yang anda baca kali ini dengan judul Reading/Writing To/From Files Using Filechannel Together With Bytebuffer Inwards Java, kami telah mempersiapkan artikel ini dengan baik untuk anda baca dan ambil informasi didalamnya. mudah-mudahan isi postingan Artikel core java, Artikel Java File Tutorial, Artikel Java NIO Tutorial, yang kami tulis ini dapat anda pahami. baiklah, selamat membaca.

Judul : Reading/Writing To/From Files Using Filechannel Together With Bytebuffer Inwards Java
link : Reading/Writing To/From Files Using Filechannel Together With Bytebuffer Inwards Java

Baca juga


Reading/Writing To/From Files Using Filechannel Together With Bytebuffer Inwards Java

In the past, I conduct keep talked nearly RandomAccessFile together with how it tin move used for doing faster IO inward Java, together with  in this Java NIO tutorial, nosotros are going to encounter how to move read/write information from using FileChannel together with ByteBuffer. Channel provides an alternate agency to read information from a file, it provides amend surgical physical care for than InputStream or OutputStream. It tin likewise move opened inward blocking together with non-blocking mode. Though FileChannles are read/write channels together with they are e'er blocking, they cannot move set into non-blocking mode. The RandomAccessFile cast treats a file equally an array of Bytes. You tin write your information inward whatever seat of the Array together with you lot tin read from whatever position. To practice that, it uses a pointer that holds the electrical current seat together with provides several methods similar seek() to motility that pointer.

Once you lot are inward the correct position, you lot tin acquire the FileChannel from RandomAccessFile and starting reading information from a file. By the way, JDK vii likewise introduced NIO 2, which makes dealing amongst files together with directory fifty-fifty easier. Read Pro Java vii NIO.2 past times Anghel Leonard to larn to a greater extent than about.



How to read/write files using FileChannel together with ByteBuffer

Before foremost coding, let's revise the basic concept of Channel together with Buffer inward Java NIO. In ane word, buffers piece of employment amongst the channel. Channels are the subway scheme through which information is transferred together with buffers are the root together with target of those information transfer. In the instance of a write, information you lot desire to write is placed inward a buffer, which is passed to a channel than channel read that information from the buffer together with write into the file.

Similarly inward instance of a read, a channel puts information inward a buffer you lot supply a file, network or whatever other source. Since the same buffer is used for reading together with writing i.e. you lot write information into the buffer but channel reads it for writing into the file, you lot must telephone telephone the flip() method ane time you lot are done writing into the buffer. The flip() method changes the pointers together with allows you lot to read information from the buffer. There are 3 types of the buffer inward Java, direct, non-direct together with mapped buffer. We volition move the straight byte buffer inward this example.



Steps to read/write information using FileChannel together with Buffer

Here is the measuring past times measuring guide to starting reading information from a file using RandomAccessFile, FileChannel, together with ByteBuffer:
  1. Open the file you lot desire to read/write using RandomAccessFile inward read/write mode.
  2. Call the getChannel() method of RandomAccessFile to acquire the FileChannel. The seat of the returned channel volition e'er move equal to this object's file-pointer offset equally returned past times the getFilePointer() method.
  3. Create a ByteBuffer using ByteBuffer.allocate() method.
  4. Store the information into ByteBuffer using diverse put() method e.g. putInt(), putLong().
  5. Flip the Buffer thence that Channel tin read information from the buffer together with write into a file. The flip() method changes the pointers together with allows you lot to read information from the buffer. 
  6. Call the write() method of FileChannel.
  7. Close the FileChannel
  8. Close the RandomAccessFile.


Another of import signal to Federal Reserve notation is that you lot tin move the same buffer for reading together with writing, but you lot take away to flip it. Now, let's encounter a sample Java plan to read/write information from files using FileChannel together with ByteBuffer inward Java. After Memory Mapped File, this is the second fastest way to read together with write from a file in Java.




Java Program to read/writes from file using FileChannel together with ByteBuffer
Here is sample plan to demonstrate how you lot tin read together with write information from a file (can move binary or text file) using FileChannel together with ByteBuffer class. I conduct keep likewise used abstraction to create an interface called Persistable, which provides 2 methods persist() together with recover(). Any object which implement this interface tin move saved together with loaded, but how practice you lot salvage together with charge them is left to the implementor i.e. you lot tin move Chanel together with Buffer similar nosotros conduct keep done or you lot tin move the old approach to read/write file inward Java.

import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel;  /**  * Java Program to read together with write on RandomAccessFile inward Java  * using FileChannle together with ByteBuffer.  *  * @author Javin  */ public class FileChannelDemo {      public static void main(String args[]) {          Tablet ipad = new Tablet("Apple", true, 1000);         System.out.println("Writing into RandomAcessFile : " + ipad);         write("tablet.store", ipad);          Tablet fromStore = new Tablet();         read("tablet.store", fromStore);         System.out.println("Object read from RandomAcessFile : " + fromStore);      }      /*      * Method to write information into File using FileChannel together with ByteBuffeer      */     public static void write(String filename, Persistable object) {         try {             // Creating RandomAccessFile for writing             RandomAccessFile shop = new RandomAccessFile("tablet", "rw");              // getting FileChannel from file             FileChannel channel = store.getChannel();              // creating together with initializing ByteBuffer for reading/writing data             ByteBuffer buffer = ByteBuffer.allocate(2048);              // an instance of Persistable writing into ByteBuffer             object.persist(buffer);              // flip the buffer for writing into file             buffer.flip();             int numOfBytesWritten = channel.write(buffer); // writing into File             System.out.println("number of bytes written : " + numOfBytesWritten);             channel.close(); // closing file channel             store.close(); // closing RandomAccess file          } catch (FileNotFoundException e) {             e.printStackTrace();         } catch (IOException e) {             e.printStackTrace();         }     }       /*      * Method to read information from File using FileChannel together with ByteBuffeer      */     public static void read(String filename, Persistable object) {         try {             // Opening RandomAccessFile for reading data             RandomAccessFile shop = new RandomAccessFile("tablet", "rw");              // getting file channel             FileChannel channel = store.getChannel();              // preparing buffer to read information from file             ByteBuffer buffer = ByteBuffer.allocate(1024);              // reading information from file channel into buffer             int numOfBytesRead = channel.read(buffer);             System.out.println("number of bytes read : " + numOfBytesRead);              // You take away to filp the byte buffer earlier reading             buffer.flip();              // Recovering object             object.recover(buffer);              channel.close();             store.close();          } catch (FileNotFoundException e) {             e.printStackTrace();         } catch (IOException e) {             e.printStackTrace();         }     } }


Our interface to abstract reading together with writing mechanism. This is likewise the actual move of the interface, supply abstraction, separating what to practice from how to do. Like this interface merely tell persist together with recover, doesn't tell how you lot practice that.

interface Persistable {      public void persist(ByteBuffer buffer);      public void recover(ByteBuffer buffer); }


Concrete cast to implement Persistable to build them readable together with writable

class Tablet implements Persistable {      private String brand;     private boolean isCellular;     private long cost; // inward U.S.A. of America Dollars      public Tablet() {         build = "";     }      public Tablet(String brand, boolean isCellular, long cost) {         this.brand = brand;         this.isCellular = isCellular;         this.cost = cost;     }      public final String getBrand() {         return brand;     }      public final boolean isCellular() {         return isCellular;     }      public final long getCost() {         return cost;     }      public final void setBrand(String brand) {         this.brand = brand;     }      public final void setCellular(boolean isCellular) {         this.isCellular = isCellular;     }      public final void setCost(long cost) {         this.cost = cost;     }      @Override     public void persist(ByteBuffer buffer) {         byte[] strBytes = brand.getBytes();         buffer.putInt(strBytes.length);         buffer.put(strBytes, 0, strBytes.length);         buffer.put(isCellular == true ? (byte) 1 : (byte) 0);         buffer.putLong(cost);     }      @Override     public void recover(ByteBuffer buffer) {         int size = buffer.getInt();         byte[] rawBytes = new byte[size];         buffer.get(rawBytes, 0, size);         this.brand = new String(rawBytes);         this.isCellular = buffer.get() == 1 ? true : false;         this.cost = buffer.getLong();     }      @Override     public String toString() {         return "Tablet [brand=" + build + ", isCellular=" + isCellular + ", cost=" + terms + "]";     }  }      Output: Writing into RandomAcessFile : Tablet [brand=Apple, isCellular=true, cost=1000] discover of bytes written : 18 discover of bytes read : 1024 Object read from RandomAcessFile : Tablet [brand=Apple, isCellular=true, cost=1000]


Caution
Don't forget to flip the byte buffer subsequently writing contents of the object into it, because file channel needs to read it inward gild to write information into RandomAccessFile. If you lot forget to telephone telephone the flip() method earlier calling the FileChannel.write() thence you lot destination upwardly writing cypher into the file.

Similarly, subsequently reading information from the file into the buffer, flip it ane time again thence that you lot tin read information from a buffer to pop contents of an object. Many Java programmer does this error of non flipping subsequently writing together with destination upwardly debugging hours because either cypher is written to file or cypher they tin read from a file.

That's all nearly how to read/write a File using FileChannel together with ByteBuffer inward Java. In this demon, I conduct keep shown you lot how to read together with write a RandomAccessFile using FileChannel together with ByteBuffer, but you lot tin apply the same technique to read whatever other text or binary file from Java program.

Further Learning
Complete Java Masterclass
solution)
How to read file business past times business inward Java using BufferedReader together with Scanner? (answer)
How to read/write Excel file inward Java? (program)
How to read CSV file inward Java? (program)
How to append information into existing file inward Java? (answer)
Pro Java vii NIO.2 past times Anghel Leonard (read here)



Demikianlah Artikel Reading/Writing To/From Files Using Filechannel Together With Bytebuffer Inwards Java

Sekianlah artikel Reading/Writing To/From Files Using Filechannel Together With Bytebuffer Inwards Java kali ini, mudah-mudahan bisa memberi manfaat untuk anda semua. baiklah, sampai jumpa di postingan artikel lainnya.

Anda sekarang membaca artikel Reading/Writing To/From Files Using Filechannel Together With Bytebuffer Inwards Java dengan alamat link https://bestlearningjava.blogspot.com/2017/05/readingwriting-tofrom-files-using.html

Belum ada Komentar untuk "Reading/Writing To/From Files Using Filechannel Together With Bytebuffer Inwards Java"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel