package Demo3;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
public class ChannelTransform {
private static String filePath = "D:\\2.txt";
public static void main(String[] args) {
transferfrom();
transferto();
}
private static void transferfrom()
{
FileChannel fromChannel = null;
FileChannel toChannel = null;
try {
fromChannel = new RandomAccessFile(filePath, "rw").getChannel();
toChannel = new RandomAccessFile("D:\\3.txt", "rw").getChannel();
long count = fromChannel.size();
//从src(fromChannel)留到toChannel
toChannel.transferFrom(fromChannel, 0, count);
//fromChannel.transferFrom(fromChannel, 0, count);这句话是没效果的
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fromChannel.close();
toChannel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static void transferto()
{
FileChannel fromChannel = null;
FileChannel toChannel = null;
try {
fromChannel = new RandomAccessFile(filePath, "rw").getChannel();
toChannel = new RandomAccessFile("D:\\4.txt", "rw").getChannel();
//从fromChannel流向目标toChannel(target)
long n = fromChannel.transferTo(0, fromChannel.size(), toChannel);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fromChannel.close();
toChannel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
nio 通道交流(复制文件小案例)API(三)
于 2017-06-02 15:38:29 首次发布