Java实现文件拷贝的4种方法
使用 java 进行文件拷贝 相信很多人都会用,,不过效率上是否最好呢?
最近看了看NIO决定试一试 java NIO 到底有什么性能的提升.
第一种方法:古老的方式
public static long forJava(File f1,File f2) throws Exception{
long time=new Date().getTime();
int length=2097152;
FileInputStream in=new FileInputStream(f1);
FileOutputStream out=new FileOutputStream(f2);
byte[] buffer=new byte[length];
while(true){
int ins=in.read(buffer);
if(ins==-1){
in.close();
out.flush();
out.close();
return new Date().getTime()-time;
}else
out.write(buffer,0,ins);
}
}
方法的2参数分别是原始文件,和拷贝的目的文件.这里不做过多介绍.
实现方法很简单,分别对2个文件构建输入输出流,并且使用一个字节数组作为我们内存的缓存器, 然后使用流从f1 中读出数据到缓存里,在将缓存数据写到f2里面去.这里的缓存是2MB的字节数组
第2种方法:使用NIO中的管道到管道传输
public static long forTransfer(File f1,File f2) throws Exception{
long time=new Date().getTime();
int length=2097152;
FileInputStream in=new FileInputStream(f1);
FileOutputStream out=new FileOutputStream(f2);
FileChannel inC=in.getChannel();
FileChannel outC=out.getChannel();
int i=0;
while(true){
if(inC.position()==inC.size()){
inC.close();
outC.cl
相关文档:
game
server responsibility:
Initialize
the server socke;
Wait
for a client to connect;
Accept
the client connection;
Create
a daemon thread to support the clien;
Go
back to step 2.
game daemon responsibility:
Accept
client player connection;
Pair
......
JAVA程序员面试32问
第一,谈谈final, finally, finalize的区别。
final 修饰符(关键字)如果一个类被声明为final,意味着它不能再派生出新的子类,不能作为父类被继承。因此一个类不能既被声明为 abstract的,又被声明为final的。将变量或方法声明为final,可以保证它们在使用中不被改变。被声明为final的变量必须在声 ......
JAVA程序员必去的网站
2008-08-19 16:35
英文网站
http://www.javaalmanac.com - Java开发者年鉴一书的在线版本,想要快速查到某种Java技巧的用法及示例的代码这是一个不错的去处.
http://www.onjava.com - O'Reilly的Java网站. 每周都有新文章.
http://java.sun.com - 官方的Java开发者网站 - 每周都有新文章发表. ......
public class DealLockTest implements Runnable {
static String i = new String();
static String j = new String();
private String str = null;
public DealLockTest(String str) {
this.str = str;
}
public static void main(String[] args) {
new Thread(new DealLockTest("i")).start( ......