public class TestNio {
public static void main(String[] args) throws Exception {
String infile = "d:\\3.zip";
String outfile = "d:\\4.zip";
test1(infile,outfile);
//test2(infile,outfile);
test3(infile,outfile);
}
public static void test3(String infile ,String outfile) throws Exception {
Long start = System.currentTimeMillis();
FileInputStream fin = null;
FileOutputStream fout = null;
// 获取输入输出通道
FileChannel fcin = null;
FileChannel fcout = null;
// ByteArrayOutputStream bsos = new ByteArrayOutputStream();
try {
fin = new FileInputStream(infile);
fout = new FileOutputStream(outfile);
//获取通道
fcin = fin.getChannel();
fcout = fout.getChannel();
// 创建缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
// fcout.transferFrom(fcin,0,fcin.size());
while ( fcin.read(buffer) != -1) {
// flip方法让缓冲区可以将新读入的数据写入另一个通道
buffer.flip();
fcout.write(buffer);
// bsos.write(buffer.array(),0,i);
// clear方法重设缓冲区,使它可以接受读入的数据
buffer.clear();
}
Long end = System.currentTimeMillis();
System.out.println("=============>"+(end-start)+"==========>"); //1,558,867 1,560,576
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fin != null) {
fin.close();
}
if (fout != null) {
fout.close();
}
if (fcin != null) {
fcin.close();
}
if (fcout != null) {
fcout.close();
}
}
}
public static void test2(String infile,String outfile) throws Exception {
Long start = System.currentTimeMillis();
// 获取源文件和目标文件的输入输出流
FileInputStream fin = null;
FileOutputStream fout = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
fin = new FileInputStream(infile);
fout = new FileOutputStream(outfile);
bis = new BufferedInputStream(fin);
bos = new BufferedOutputStream(fout);
byte[] buf = new byte[1024];
int len = bis.read(buf);
while ( len != -1){
bos.write(buf,0,len);
len = bis.read(buf);
}
bos.close();
bis.close();
Long end = System.currentTimeMillis();
System.out.println("=============>"+(end-start));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fout != null) {
fout.close();
}
if (fin != null) {
fin.close();
}
}
}
public static void test1(String infile,String outfile) throws Exception {
Long start = System.currentTimeMillis();
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(infile);
fos = new FileOutputStream(outfile);
byte[] buffer = new byte[1024];
int len = -1;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
Long end = System.currentTimeMillis();
System.out.println("=============>"+(end-start)+"==========>");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}