本文共 2996 字,大约阅读时间需要 9 分钟。
用filechannel更方便一些
-
-
-
-
- public final class CopyFiles {
-
-
-
-
- public static final String INPUT_FILE = "C:\\TEMP\\cottage.jpg";
-
-
-
-
-
-
- public static final String COPY_FILE_TO = "C:\\TEMP10\\cottage_2.jpg";
-
-
- public static void main(String... aArgs) throws IOException{
- File source = new File(INPUT_FILE);
- File target = new File(COPY_FILE_TO);
- CopyFiles test = new CopyFiles();
- test.copyWithChannels(source, target, false);
-
- log("Done.");
- }
-
-
- private void copyWithChannels(File aSourceFile, File aTargetFile, boolean aAppend) {
- log("Copying files with channels.");
- ensureTargetDirectoryExists(aTargetFile.getParentFile());
- FileChannel inChannel = null;
- FileChannel outChannel = null;
- FileInputStream inStream = null;
- FileOutputStream outStream = null;
- try{
- try {
- inStream = new FileInputStream(aSourceFile);
- inChannel = inStream.getChannel();
- outStream = new FileOutputStream(aTargetFile, aAppend);
- outChannel = outStream.getChannel();
- long bytesTransferred = 0;
-
- while(bytesTransferred < inChannel.size()){
- bytesTransferred += inChannel.transferTo(0, inChannel.size(), outChannel);
- }
- }
- finally {
-
- if (inChannel != null) inChannel.close();
- if (outChannel != null) outChannel.close();
- if (inStream != null) inStream.close();
- if (outStream != null) outStream.close();
- }
- }
- catch (FileNotFoundException ex){
- log("File not found: " + ex);
- }
- catch (IOException ex){
- log(ex);
- }
- }
-
- private void copyWithStreams(File aSourceFile, File aTargetFile, boolean aAppend) {
- log("Copying files with streams.");
- ensureTargetDirectoryExists(aTargetFile.getParentFile());
- InputStream inStream = null;
- OutputStream outStream = null;
- try{
- try {
- byte[] bucket = new byte[32*1024];
- inStream = new BufferedInputStream(new FileInputStream(aSourceFile));
- outStream = new BufferedOutputStream(new FileOutputStream(aTargetFile, aAppend));
- int bytesRead = 0;
- while(bytesRead != -1){
- bytesRead = inStream.read(bucket);
- if(bytesRead > 0){
- outStream.write(bucket, 0, bytesRead);
- }
- }
- }
- finally {
- if (inStream != null) inStream.close();
- if (outStream != null) outStream.close();
- }
- }
- catch (FileNotFoundException ex){
- log("File not found: " + ex);
- }
- catch (IOException ex){
- log(ex);
- }
- }
-
- private void ensureTargetDirectoryExists(File aTargetDir){
- if(!aTargetDir.exists()){
- aTargetDir.mkdirs();
- }
- }
-
- private static void log(Object aThing){
- System.out.println(String.valueOf(aThing));
- }
- }
本文转自sucre03 51CTO博客,原文链接:http://blog.51cto.com/sucre/652052,如需转载请自行联系原作者