The recent use of NIO to read files, English normal, reading Chinese will appear garbled, after the search can be used CharSet class to solve:
The code is as follows:
Package Com.example.demo;
Import java.io.FileNotFoundException;
Import Java.io.RandomAccessFile;
Import Java.nio.ByteBuffer;
Import Java.nio.CharBuffer;
Import Java.nio.channels.FileChannel;
Import Java.nio.charset.Charset;
Import Java.nio.charset.CharsetDecoder; public class Niodemo {public static void main (string[] args) {try {Charset Charset = charset.forname ("GBK");//jav The A.nio.charset.charset handles character conversion issues.
It converts character sequences into byte and inverse conversions by constructing charsetencoder and Charsetdecoder.
Charsetdecoder decoder = Charset.newdecoder ();
Randomaccessfile RAF = new Randomaccessfile ("D:\\d\\test.txt", "RW");
FileChannel FC = Raf.getchannel ();
Bytebuffer buffer = bytebuffer.allocate (512);
Charbuffer cb = charbuffer.allocate (512);
int count = fc.read (buffer);
while (count! =-1) {System.out.println ("Count =" +count);
Buffer.flip ();
Decoder.decode (buffer, CB, FALSE);
Cb.flip ();
while (Cb.hasremaining ()) {System.out.print (Cb.get ());} System.out.println ();
Buffer.clear ();
Cb.clear ();
Count = fc.read (buffer);
} raf.close ();
} catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
}
}
}
Test.. TXT style is as follows:
According to the British Daily Express, Einstein argues that one way to travel through time to the future is to travel at the speed of light in the universe. This widely accepted theory says that time travel must build a spaceship capable of flying at the speed of light and into space.
Briangreene, a theoretical physicist and Columbia University, said: "You can build a spaceship, go into space and travel at near speed of light, turn a circle and come back." Imagine that you flew for six months and then turned around and flew back for another six months. ”
Operation Result: