共計(jì) 827 個(gè)字符,預(yù)計(jì)需要花費(fèi) 3 分鐘才能閱讀完成。
在 Java 中,transferTo
是 FileChannel
類的一個(gè)方法,用于將文件通道中的數(shù)據(jù)直接傳輸?shù)搅硪粋€(gè)文件通道中。以下是使用 transferTo
方法的示例代碼:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class FileTransferExample {public static void main(String[] args) {try (FileInputStream in = new FileInputStream("source.txt");
FileOutputStream out = new FileOutputStream("destination.txt")) {FileChannel inChannel = in.getChannel();
FileChannel outChannel = out.getChannel();
long transferred = inChannel.transferTo(0, inChannel.size(), outChannel);
System.out.println("Transferred " + transferred + " bytes");
} catch (IOException e) {e.printStackTrace();
}
}
}
在上面的示例中,首先創(chuàng)建一個(gè)輸入文件流和一個(gè)輸出文件流,然后分別獲取它們的文件通道。接下來,調(diào)用 transferTo
方法將輸入文件通道中的數(shù)據(jù)直接傳輸?shù)捷敵鑫募ǖ乐?,并返回傳輸?shù)淖止?jié)數(shù)。最后,在控制臺(tái)打印出傳輸?shù)淖止?jié)數(shù)。
需要注意的是,在使用 transferTo
方法時(shí),需要確保兩個(gè)文件通道都處于可讀寫狀態(tài),并且要注意處理可能拋出的 IOException
異常。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完
發(fā)表至: Java
2024-05-27