读取一个文件的内容,然后写入另外一个文件
public class NioTest4 { public static void main(String[] args) throws Exception {
FileInputStream inputStream = new FileInputStream("input.txt"); FileOutputStream outputStream = new FileOutputStream("output.txt"); FileChannel inputChannel = inputStream.getChannel();
FileChannel outputChannel = outputStream.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true){
buffer.clear();
int read = inputChannel.read(buffer);
if( -1 == read){
break;
}
buffer.flip(); outputChannel.write(buffer); }
inputChannel.close();
outputChannel.close(); }}
通过NIO读取文件涉及3个步骤
1、从FileInputStream获取FileChannel对象
2、创建Buffer
3、将数据从Channel读取到Buffer中
绝对方法与相对方法的含义
1、相对方法: limit值与position值会在操作时被考虑到
2、绝对方法: 完全忽略调limit值和position值。