import java.nio.*; import java.nio.channels.*; import java.io.*; public class FileChannelTest3 { public FileChannelTest3(String srcFilename, String destFilename) { System.out.println("どちらの方法でコピーしますか"); System.out.println("1: TransferTo 2: TransferFrom"); System.out.print("> "); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try{ String inputText = reader.readLine(); if (inputText.equals("1")) { copyUsingTransferTo(srcFilename, destFilename); }else if (inputText.equals("2")) { copyUsingTransferFrom(srcFilename, destFilename); } }catch(IOException ex){ ex.printStackTrace(); } } private void copyUsingTransferTo(String srcFilename, String destFilename){ System.out.println("TransferTo を使用してコピーを行います"); try{ FileInputStream in = new FileInputStream(srcFilename); FileChannel inputChannel = in.getChannel(); FileOutputStream out = new FileOutputStream(destFilename); FileChannel outputChannel = out.getChannel(); inputChannel.transferTo(0, (int)inputChannel.size(), outputChannel); outputChannel.close(); inputChannel.close(); }catch(FileNotFoundException ex){ ex.printStackTrace(); }catch(IOException ex){ ex.printStackTrace(); } } private void copyUsingTransferFrom(String srcFilename, String destFilename){ System.out.println("TransferTo を使用してコピーを行います"); try{ FileInputStream in = new FileInputStream(srcFilename); FileChannel inputChannel = in.getChannel(); FileOutputStream out = new FileOutputStream(destFilename); FileChannel outputChannel = out.getChannel(); outputChannel.transferFrom(inputChannel, 0, (int)inputChannel.size()); outputChannel.close(); inputChannel.close(); }catch(FileNotFoundException ex){ ex.printStackTrace(); }catch(IOException ex){ ex.printStackTrace(); } } public static void main(String[] args){ new FileChannelTest3(args[0], args[1]); } }