Copy files (file input and output streams) in Java and java
Import java. io. bufferedInputStream; import java. io. bufferedOutputStream; import java. io. file; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. fileOutputStream; import java. io. IOException; public class CopyFileDemo {public static void main (String [] args) {copyFile ("c: \ a.txt", "d: \ B .txt ");} private static final int OUTPUT_FILE_BUFFER_SIZE = 4*1024; private static boo Lean copyFile (String srcdir, String desdir) {// file stream FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; // use cached BufferedInputStream bis; BufferedOutputStream bos; // The length of each read int readLength = 0; // The current position int position = 0; // print the information System. out. println ("copyFile srcdir:" + srcdir + "desdir:" + desdir); // target File disFileInfo = null; // source File information File fileInfo = new File (srcdir ); if (! FileInfo. exists () {System. out. println ("return false if the source file does not exist"); return false;} // defines the cache size byte [] buffer = new byte [OUTPUT_FILE_BUFFER_SIZE]; try {fileInputStream = new FileInputStream (fileInfo);} catch (FileNotFoundException e) {e. printStackTrace (); return false;} // buffered input stream bis = new BufferedInputStream (fileInputStream, 0x4000 ); // check whether the target File has the created File disFileInfo = new File (desdir); if (! DisFileInfo. exists () {try {disFileInfo. createNewFile ();} catch (IOException e) {e. printStackTrace (); return false ;}try {fileOutputStream = new FileOutputStream (disFileInfo);} catch (FileNotFoundException e) {e. printStackTrace (); return false;} // buffered output stream bos = new BufferedOutputStream (fileOutputStream, 0x10000); while (position! = FileInfo. length () {if (position! = FileInfo. length ()) {try {// {@/* Core code * // read each byte from the given offset in the byte input stream to buffer readLength = bis in the specified byte array. read (buffer, 0, OUTPUT_FILE_BUFFER_SIZE); // write the len bytes in the specified byte array buffer starting from offset off to the output stream bos of this buffer. write (buffer, 0, readLength); position + = readLength; //} catch (IOException e) {e. printStackTrace (); return false ;}}// close the stream if (bis! = Null) {try {bis. close () ;}catch (IOException e) {e. printStackTrace (); return false ;}} if (bos! = Null) {try {bos. close ();} catch (IOException e) {e. printStackTrace (); return false ;}} if (position = fileInfo. length () {System. out. println ("copyFile success !! "); Return true;} return false ;}}