Package io;//: Io/buffertotext.java//converting text to and from Bytebuffersimport Java.nio.*;import java.nio.channels. *;import java.nio.charset.*;import java.io.*;/* * Convert data: * buffers contain normal bytes, in order to convert them into characters, either decode them at the time of input, or decode them from the buffer output. */public class Buffertotext {private static final int bsize = 1024;public static void Main (string[] args) throws Exception {FileChannel FC = new FileOutputStream ("Data2.txt"). Getchannel (); Fc.write (Bytebuffer.wrap ("Some text". GetBytes ())); Fc.close (); FC = new FileInputStream ("Data2.txt"). Getchannel (); Bytebuffer buff = bytebuffer.allocate (bsize); Fc.read (Buff); Buff.flip (); Doesn ' t work:System.out.println (Buff.ascharbuffer ()); Decode using this system ' s default Charset:buff.rewind (); String encoding = System.getproperty ("file.encoding"); SYSTEM.OUT.PRINTLN ("decoded using" + Encoding + ":" + charset.forname (encoding). Decode (buff)); Or, we could encode with something that would PRINT:FC = new FileOutputStream ("Data2.txt"). Getchannel (); Fc.wriTe (Bytebuffer.wrap ("Some text". GetBytes ("Utf-16be")); Fc.close (); Now try reading AGAIN:FC = new FileInputStream ("Data2.txt"). Getchannel (); Buff.clear (); Fc.read (Buff); Buff.flip (); System.out.println (Buff.ascharbuffer ()); Use a charbuffer to write THROUGH:FC = new FileOutputStream ("Data2.txt"). Getchannel (); Buff = Bytebuffer.allocate (24); More than needed Buff.ascharbuffer (). Put ("Some text"); Fc.write (Buff); Fc.close (); Read and DISPLAY:FC = new FileInputStream ("Data2.txt"). Getchannel (); Buff.clear (); Fc.read (Buff); Buff.flip (); System.out.println (Buff.ascharbuffer ());}}
Java file Byte character data conversion