java NIO实现的文件复制(包括文件与文件夹复制) NIO读取数据与写数据

本文详细介绍了如何使用Java的非阻塞I/O(NIO)API进行文件和文件夹的复制操作,包括读取和写入数据的关键步骤。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;



//NIO读数据
public class NIOReadAndWrite {
public void readTest(File fileName){
String content = null;
FileInputStream fis = null;
FileChannel fc = null;
try {
fis = new FileInputStream(fileName);
fc = fis.getChannel();
ByteBuffer bb = ByteBuffer.allocate(10000);
fc.read(bb);
bb.flip();
content = new String(bb.array());
System.out.println(content);
fc.close();
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

//NIO写数据

public void writeTest(File file){
String str = "dfkvmlsmvhsdgkahkanckjbasdchbsdkcsklcnjsbckjsbcvls";
FileOutputStream fos = null;
FileChannel fc = null;
byte[] b = str.getBytes();
System.out.println(str.getBytes());
try {
fos = new FileOutputStream(file,true);
fc = fos.getChannel();
ByteBuffer bb = ByteBuffer.allocate(b.length);
bb.put(b);
bb.flip();
fc.write(bb);
fc.close();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

//NIO复制数据

public void copyFile(String oldPath,String newPath)throws IOException{
long starttime = System.currentTimeMillis();
ByteBuffer bb = ByteBuffer.allocate(100000);
File oldf = new File(oldPath);
File newf = new File(newPath);
if(!newf.exists()){
newf.mkdirs();
}


int len = -1;
File temp = null;
String[] list = oldf.list();
for(int i=0;i<list.length;i++){
if(oldPath.endsWith(File.separator)){
temp = new File(oldPath+list[i]);
}else{
temp = new File(oldPath+File.separator+list[i]);
}
System.out.println(temp.isFile());
if(temp.isFile()){
FileInputStream fis = new FileInputStream(temp);
FileChannel in = fis.getChannel();

FileOutputStream fos = new FileOutputStream(newf+"/"+temp.getName().toString());
FileChannel out = fos.getChannel();
while((len=in.read(bb)) != -1){
bb.flip();
out.write(bb);
bb.clear();
}
out.close();
fos.close();
in.close();
fis.close();
}
if(temp.isDirectory()){
copyFile(oldPath+"/"+list[i], newPath+"/"+list[i]);
}
}


long endtime = System.currentTimeMillis();
System.out.println("复制总时长:"+(endtime - starttime));

}

public static void main(String[] args) throws IOException{
//File file = new File("d:/test.txt");
String oldFile = "D:\\VC98";
String newFile = "E:/猎豹下载/111";
//new NIOReadAndWrite().readTest(file);
//new NIOReadAndWrite().writeTest(file);
new NIOReadAndWrite().copyFile(oldFile,newFile);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值