都說java的NI/O很快,我也不知道快不快 沒做測試沒有發言權。網上剽竊了一段代碼。貼上。感覺還可以。
/**
* @Title: FileTransfer.java ,By gumutianqi at 2011-2-24上午11:16:18
* @version: 1.0
*
* @Description : this is you mark
* @Company: Copyright (c) 2011 AOSA TECH Ltd. All right reserved
* @Project: SafeMedia
*
*/
package aosa.safemedia;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
/**
* @Title FileTransfer
* @author yangtao at 2011-3-9下午04:34:36
* @Description 文件傳輸類
*/
public class FileTransfer {
// 要傳輸的文件
private File file;
// 文件傳輸的進度
private int fileOffset;
// 每次文件傳輸的大小。
private static int size = 1024 * 8;
public FileTransfer() {
}
/**
* @param source源文件
* 。target目的文件。
* @Description 傳輸文件。
*/
public void transFile(File source, File target) {
try {
//ByteBuffer byteBuffer = ByteBuffer.allocate(size);
FileInputStream fileInputStream = new FileInputStream(source);
FileOutputStream fileOutputStream = new FileOutputStream(target);
FileChannel fileInputChannel = fileInputStream.getChannel();
FileChannel fileOutputChannel = fileOutputStream.getChannel();
while (true) {
if (fileInputChannel.position() == fileInputChannel.size()) {
fileInputChannel.close();
fileOutputChannel.close();
return;
}
if (fileInputChannel.size() - fileInputChannel.position() < size) {
size = (int) (fileInputChannel.size() - fileInputChannel
.position());
}
fileInputChannel.transferTo(fileInputChannel.position(), size, fileOutputChannel);
fileInputChannel.position(fileInputChannel.position() + size);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @param sourceFilePath
* 源文件路徑
* @param targetFilePath
* 目標文件路徑
* @Description 根據文件路徑獲得文件然后用于傳輸。
*/
public void transFile(String sourceFilePath, String targetFilePath) {
File source = new File(sourceFilePath);
File target = new File(targetFilePath);
transFile(source, target);
}
public static void main(String[] args) {
FileTransfer transfer = new FileTransfer();
transfer.transFile("F:\\sharesrc\\1.png", "F:\\sharedest\\1.png");
}
}
代碼還有點不完善,還得修改修改。