小练习:nio读写文件,将fileread中的内容读取到filewrite中
try {
//创建输入通道
FileInputStream fis = new FileInputStream("F:/iotest/readfile.txt");
FileChannel readChannel = fis.getChannel();
//创建缓冲区
ByteBuffer buffer = ByteBuffer.allocate();
//创建输出通道
FileOutputStream fos = new FileOutputStream("F:/iotest/filewrite.txt");
FileChannel writeChannel = fos.getChannel(); while (true) {
buffer.clear();
//将文件内容读到缓冲区中
int mark = readChannel.read(buffer);
if (mark==-) {
break;
}
buffer.flip();
writeChannel.write(buffer);
} } catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
代码运行前:
readfile:
filewrite:
代码运行后:
readfile:
filewrite: