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() {
// TODO Auto-generated method stub
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) {
// TODO: handle exception
e.printStackTrace();
}
}
public static void writeFileByNIO() {
// TODO Auto-generated method stub
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) {
// TODO: handle exception
e.printStackTrace();
}
}
}
JAVA-NIO
最新推荐文章于 2022-12-09 10:36:16 发布