java NIO複製文件總結 最快的兩種方法

普通複製方法就不總結。

第一種:FileChanel.transferTo(0, size, out)

第二種:Files.copy(source, out)

兩種都是NIO包下類。

第一種使用方法:

	public static void test3(){
		//輸出7366ms
		long start = System.currentTimeMillis();
		System.out.println("writeBuffer-開始時間:"+start);
		FileChannel fci = null;
		FileChannel fco = null;
		try {
			fci = new RandomAccessFile("D:\\Eclipse\\workspace\\sdutent\\file1.txt", "rw").getChannel();
			fco = new RandomAccessFile("‪fileX.txt", "rw").getChannel();
			fci.transferTo(0, fci.size(), fco);
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(fci!=null) {
					fci.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			try {
				if(fco!=null) {
					fco.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		long end = System.currentTimeMillis();
		System.out.println("總消耗:"+(end-start));
	}

第二種使用方法:

	public static void test2() throws IOException {
		long start = System.currentTimeMillis();
		System.out.println("writeBuffer-開始時間:"+start);
		Files.copy(new File("D:\\Eclipse\\workspace\\sdutent\\file1.txt").toPath(), new FileOutputStream("‪fileX.txt"));
		long end = System.currentTimeMillis();
		System.out.println("總消耗:"+(end-start));
	}

兩種方法在單線程下效率差不多。都是利用了NIO種的新特性--通道。

但是第一種方法更靈活,第二種比較簡單。

FileChannel是線程安全的,所以可以利用多線程來進行復制文件,比如將文件分成4塊,然後起4個線程去操作,這樣效率提升的更明顯。

PS:Files類是Java7之後推出來的,對文件的操作功能非常牛,建議多學習。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章