使用通道和缓存区将数据写入文件中
package com.atguigu;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NIOFileChannel01
{
public static void main(String[] args) throws IOException
{
String str = "hello 马钊!";
FileOutputStream fileOutputStream = new FileOutputStream("F:\\file02.txt");
FileChannel fileChannel = fileOutputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
byteBuffer.put(str.getBytes());
byteBuffer.flip();
fileChannel.write(byteBuffer);
fileOutputStream.close();
}
}
将目标文件写入通道和缓存区
package com.atguigu;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NIOFileChannel02
{
public static void main(String[] args) throws IOException
{
File file = new File("f://file02.txt");
FileInputStream fileInputStream = new FileInputStream(file);
FileChannel channel = fileInputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate((int)file.length());
channel.read(byteBuffer);
System.out.println(new String(byteBuffer.array()));
fileInputStream.close();
}
}
使用通道和缓存区对文件进行拷贝
package com.atguigu;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NIOFileChannel03
{
public static void main(String[] args) throws IOException
{
FileInputStream fileInputStream = new FileInputStream("1.txt");
FileChannel fileChannel01 = fileInputStream.getChannel();
FileOutputStream fileOutputStream = new FileOutputStream("2.txt");
FileChannel fileChannel02 = fileOutputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(512);
while (true)
{
byteBuffer.clear();
int read = fileChannel01.read(byteBuffer);
if (read == -1)
{
break;
}
byteBuffer.flip();
fileChannel02.write(byteBuffer);
}
fileInputStream.close();
fileOutputStream.close();
}
}
使用transferFrom实现通道和通道之间的拷贝
package com.atguigu.nio;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
public class NIOFileChannel04 {
public static void main(String[] args) throws Exception {
FileInputStream fileInputStream = new FileInputStream("f:\\file04.txt");
FileOutputStream fileOutputStream = new FileOutputStream("f:\\file05.txt");
FileChannel sourceCh = fileInputStream.getChannel();
FileChannel destCh = fileOutputStream.getChannel();
destCh.transferFrom(sourceCh,0,sourceCh.size());
sourceCh.close();
destCh.close();
fileInputStream.close();
fileOutputStream.close();
}
}