1. 程式人生 > >黑馬程式設計師——————使用NIO對檔案進行復制(2)

黑馬程式設計師——————使用NIO對檔案進行復制(2)

由於檔案複製到檔案和檔案複製到資料夾的程式碼具有重複性,所以兩者方法可結合在一起。

分析:

1,複製到資料夾程式碼多了一層判斷:

f(!targetFile.exists())
targetFile.mkdirs();

2,當targetFile為檔案時,targetFile.mkdirs();語句會把形如**.txt檔案也建立成資料夾形式

3,複製到資料夾時,需要改變targetFile的值即:targetFile=new File(targetFile.getAbsolutePath()+"\\"+sourceFile.getName());

結論:新增判斷語if(!targetFile.isFile())

else targetFile.mkdirs();

程式碼如下:

package sample;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
//把檔案複製到資料夾或者檔案
public class Sample3 {
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		File sourceFile=new File("C:\\新建資料夾\\1\\a.txt");
		File targetFile=new File("E:/新建資料夾");
		CopyFile(sourceFile,targetFile);
	}
	public static void CopyFile(File sourceFile,File targetFile) throws IOException  {
		if(!targetFile.isFile())
			else {<span style="font-family: Arial, Helvetica, sans-serif;">	</span>
<span style="white-space:pre"></span><pre name="code" class="java"><span style="white-space:pre">				</span>targetFile.mkdirs();
<span style="white-space:pre">				</span>targetFile=new File(targetFile.getAbsolutePath()+"\\"+sourceFile.getName());
                             }
		//建立輸入輸出通道緩衝區
		FileChannel inChannel=new FileInputStream(sourceFile).getChannel();
		System.out.println("檢測2");

		FileChannel outChannel=new FileOutputStream(targetFile).getChannel();
	
		ByteBuffer buffer=ByteBuffer.allocate(1024);
		while(inChannel.read(buffer)!=-1){
			System.out.println("檢測3");
			buffer.flip();
			outChannel.write(buffer);
			buffer.clear();
		}
		inChannel.close();
		outChannel.close();
	}
}