public static long forChannel(File f1, File f2) throws Exception {
long time = new Date().getTime();
int size = 2*1024; FileInputStream in = new FileInputStream(f1);
FileOutputStream out = new FileOutputStream(f2); FileChannel inC = in.getChannel();
FileChannel outC = out.getChannel(); ByteBuffer buffer = null;
int count = size;
while (inC.position() != inC.size()) {
if ((inC.size() - inC.position()) < size) {
count = (int) (inC.size() - inC.position());
}
buffer = ByteBuffer.allocateDirect(count);
inC.read(buffer);
buffer.flip();
outC.write(buffer);
outC.force(false);
}
inC.close();
outC.close();
in.close();
out.flush();
out.close();
return new Date().getTime() - time;
}
public static long forChannelOne(File f1, File f2) throws IOException {
long time = new Date().getTime();
int size = 2 * 1024;// 2097152;
FileInputStream in = new FileInputStream(f1);
FileOutputStream out = new FileOutputStream(f2); FileChannel fcin = in.getChannel();
FileChannel fcout = out.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(size); // 分配2KB作为缓冲区
while (true) {
buffer.clear(); // 每次使用必须置空缓冲区 int r = fcin.read(buffer);
if (r == -1) {
break;
} buffer.flip(); // 写入前使用flip这个方法
fcout.write(buffer);
} fcin.close();
fcout.close(); in.close();
out.flush();
out.close();
return new Date().getTime() - time;
} public static long forJava(File f1, File f2) throws Exception {
long time = new Date().getTime();
int size = 2 * 1024;// 2097152;
FileInputStream in = new FileInputStream(f1);
FileOutputStream out = new FileOutputStream(f2); byte[] buffer = new byte[size];
int ins;
while ((ins = in.read(buffer)) != -1) {
out.write(buffer, 0, ins);
} in.close();
out.flush();
out.close();
return new Date().getTime() - time;
} public static long forTransfer(File f1, File f2) throws Exception {
long time = new Date().getTime();
int size = 2 * 1024;// 2k == 2097152;
FileInputStream in = new FileInputStream(f1);
FileOutputStream out = new FileOutputStream(f2); FileChannel inC = in.getChannel();
FileChannel outC = out.getChannel(); int count = size;
while (inC.position() != inC.size()) {
if ((inC.size() - inC.position()) < size) {
count = (int) (inC.size() - inC.position());
}
inC.transferTo(inC.position(), count, outC);
inC.position(inC.position() + count);
}
inC.close();
outC.close();
return new Date().getTime() - time;
}public void test(){
String infile = "/sdcard/testUTF.txt"; //8k
String outfile = "/sdcard/testUTF8.txt";
File f1 = new File(infile);
File f2 = new File(outfile);
try {
// Log.v("TAG", "" + Student.forJava(f1, f2));//31
// Log.v("TAG", "" + Student.forTransfer(f1, f2));//28
Log.v("TAG", "" + Student.forChannelOne(f1, f2));//22
// Log.v("TAG", "" + Student.forChannel(f1, f2));//15
} catch (Exception e) {
e.printStackTrace();
}
标签:f1,f2,NIO,new,Android,inC,out,拷贝,size From: https://blog.51cto.com/u_3124497/6914160