close

Copy a file

import java.io.*;            public class JCopy{            public static void main(String args[]){            try {            JCopy j = new JCopy();            j.copyFile(new File(args[0]),new File(args[1]));            }            catch (Exception e) {            e.printStackTrace();            }            }            public void copyFile(File in, File out) throws Exception {            FileInputStream fis  = new FileInputStream(in);            FileOutputStream fos = new FileOutputStream(out);            byte[] buf = new byte[1024];            int i = 0;            while((i=fis.read(buf))!=-1) {            fos.write(buf, 0, i);            }            fis.close();            fos.close();            }            }
[JDK1.4 using the java.nio package]
import java.nio.channels.*;            import java.io.*;            public class JCopy2{            public static void main(String args[]){            try {            JCopy2 j = new JCopy2();            j.copyFile(new File(args[0]),new File(args[1]));            }            catch (Exception e) {            e.printStackTrace();            }            }            public void copyFile(File in, File out) throws Exception {            FileChannel sourceChannel = new            FileInputStream(in).getChannel();            FileChannel destinationChannel = new            FileOutputStream(out).getChannel();            sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);            // or            //  destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size());            sourceChannel.close();            destinationChannel.close();            }            }
NOTE:
In win2000 , the transferTo() does not transfer files > than 2^31-1 bytes. it throws an exception of "java.io.IOException: The parameter is incorrect"
In solaris8 , Bytes transfered to Target channel are 2^31-1 even if the source channel file is greater than 2^31-1
In LinuxRH7.1 , it gives an error of java.io.IOException: Input/output error

arrow
arrow
    全站熱搜

    npitt 發表在 痞客邦 留言(0) 人氣()