指定编码器、解码器,并且利用ByteBuffer读写文件。
做个例子,以后编写程序的时候使用。
做个例子,以后编写程序的时候使用。
package cxz.net;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
public class TryByteBuffer {
String url = "D:\\workspace\\target";
public static void main(String[] args) throws IOException {
// new TryMappedByteBuffer().write();
new TryMappedByteBuffer().read();
}
private void read() throws IOException {
Charset chrst = Charset.forName("UTF-16");
File f = new File(url);
FileChannel readChannel = new FileInputStream(f).getChannel();
ByteBuffer reader = ByteBuffer.allocate(1024 * 1024);
readChannel.read(reader);
reader.flip();//You need call this method befor decode~
CharBuffer charReader = chrst.decode(reader);
System.out.println("value=" + charReader.toString());
}
private void write() throws IOException {
Charset chrst = Charset.forName("UTF-16");
ByteBuffer writer = chrst.encode("Hi ~ This is a test String");
File f = new File(url);
// System.out.println(f.exists());
FileChannel writeChannel = new FileOutputStream(f, false).getChannel();
writeChannel.write(writer);
writeChannel.close();
}
}