package tx;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class a {
public static void main(String[] args) {
writeFileByNIO();
readFileByNIO();
}
public static void readFileByNIO() {
try {
FileInputStream p=new FileInputStream("D:\\nio.txt");
FileChannel k=p.getChannel();
ByteBuffer buffer =ByteBuffer.allocate(1024);
k.read(buffer);
buffer.flip();
StringBuffer sb= new StringBuffer ();
while (buffer.remaining()>0){
byte b=buffer.get();
sb.append((char)b);
}
System .out.println("读取:"+sb);
k.close();
p.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void writeFileByNIO() {
try {
File file=new File("D:\\nio.txt");
FileOutputStream n= new FileOutputStream(file);
FileChannel m=n.getChannel();
ByteBuffer buffer =ByteBuffer.allocate(1024);
String str="Hello NIO";
buffer.put(str.getBytes());
buffer.flip();
m.write(buffer);
m.close();
n.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
