File copy
File copy steps:
- 1. Establish file Agent->file source file/file destination file
- 2. Set up pipelines and build pipelines
- 3. Data Boxing
- 4. Cyclic reading, cyclic output
- 5. Close the stream
Copy of the Package folder; Import Java.io.file;import Java.io.fileinputstream;import Java.io.fileoutputstream;import Java.io.ioexception;import java.io.inputstream;import java.io.outputstream;/* * Copy of File * 1. Create Agent---source file, target file * 2. Establish the input/output pipeline * 3. Data read/write * 4. Close stream */public class CopyFile {static void CopyFile (String scrpath, String destpath) throws IO exception{CopyFile (new file (Scrpath), new file (DestPath)); } static void CopyFile (File scr,file dest) throws ioexception{if (!scr.exists ()) {SYSTEM.O UT.PRINTLN ("File does not exist"); }else if (!scr.isfile ()) {System.out.println ("source target is not a file"); }//Set up pipe inputstream fin = null; OutputStream fout = null; Establish piping fin = new FileInputStream (SCR); Fout = new FileOutputStream (dest); Data boxed byte[] Bufferbox = new byte[1024]; int len = 0; Loop read while ( -1! = (len = fin.read (Bufferbox))) {Fout.write (BuffeRbox, 0, Len); }//Close stream Fout.flush (); Fout.close (); Fin.close (); }}
Folder copy
- Copy of Folder
- 1. File--Direct copy CopyFile ()
- 2. Create mkdir () folder
- 3. Recursive search for descendant-level
Copy of the Package folder; Import java.io.file;import java.io.ioexception;/* * Folder copy * 1. Direct copy of file, CopyFile () * 2. Folder--Create mkdir () * 3. Recursive lookup descendant level */public class Copydir {public static void main (string[] args) {//folder path String Srcpath = "/users/xiejinhui/documents/mweb"; String destpath = "/users/xiejinhui/desktop/"; Create file DIRC_SRC = new files (srcpath); File dirc_dest = null; if (Dirc_src.isdirectory ()) {dirc_dest = new File (Destpath,dirc_src.getname ()); } copydirfile (Dirc_src,dirc_dest); } private static void Copydirfile (file dirc_src, file dirc_dest) {if (Dirc_src.isfile ()) {///If the file is copied directly try {copyfile.copyfile (dirc_src, dirc_dest); } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); System.out.println ("Copy file Failed"); }}else if (Dirc_src.isdirectory ()) {///If it is a folder//The target folder exists Dirc_dest.mkdirs (); Gets the next level (if the next level has the next level, recursively with a For loop) for (File Sub:d Irc_src.listfiles ()) {Copydirfile (sub, new file (d Irc_dest, Sub.getname ())); } } }}
The Copy folder has two main functions, an important method
- Two functions: 1. File copy 2. Folder creation
- An important method: recursion
10.java Copy Folder