1. Copying multi-level folder cases
Requirements: Copying multi-level folders
data Source: E:\JavaSE\day21\code\demos
Destination: E:\
Analysis:
A: Encapsulating the data source file
B: Package destination file
C: Determine if the file is a document or a folder
A: is a folder
Create the folder in the destination directory
gets all files or folders under this file object file object
iterate to get each file object
back to C
B: It's a file.
just copy (Byte stream)
2. code example:
1 Packagecn.itcast_05;2 ImportJava.io.BufferedInputStream;3 ImportJava.io.BufferedOutputStream;4 ImportJava.io.File;5 ImportJava.io.FileInputStream;6 ImportJava.io.FileOutputStream;7 Importjava.io.IOException;8 /*9 * Requirements: Duplicate multi-polar foldersTen * One * Data Source: E:\JavaSE\day21\code\demos A * Destination: E:\ - * - * Analysis: the * A: Encapsulate data source file - * B: Package destination file - * C: Determine if the file is a folder or a document - * A: is a folder + * Create this folder in the destination directory - * Gets all files or folders under this file object file object + * Iterate to get each file object A * back to C at * B: Yes file - * just copy (Byte stream) - */ - Public classCopyfoldersdemo { - Public Static voidMain (string[] args)throwsIOException { - //encapsulate Data source file inFile Srcfile =NewFile ("E:\\javase\\day21\\code\\demos"); - //Package destination File toFile DestFile =NewFile ("e:\\"); + //the ability to copy folders - CopyFolder (Srcfile, destfile); the } * Private Static voidcopyfolder (file srcfile, file destfile) $ throwsIOException {Panax Notoginseng //determine if the file is a folder or a document - if(Srcfile.isdirectory ()) { the //folder +File NewFolder =NewFile (DestFile, Srcfile.getname ()); A Newfolder.mkdir (); the //gets all files or folders under this file object file object +file[] Filearray =srcfile.listfiles (); - for(File file:filearray) { $ copyfolder (file, newfolder); $ } -}Else { - //file theFile NewFile =NewFile (DestFile, Srcfile.getname ()); - copyFile (Srcfile, newFile);Wuyi } the } - Private Static voidCopyFile (file srcfile, file newFile)throwsIOException { WuBufferedinputstream bis =NewBufferedinputstream (NewFileInputStream ( - srcfile)); AboutBufferedoutputstream BOS =NewBufferedoutputstream ( $ NewFileOutputStream (NewFile)); - byte[] Bys =New byte[1024]; - intLen = 0; - while(len = Bis.read (bys))! =-1) { ABos.write (bys, 0, Len); + } the bos.close (); - bis.close (); $ } the}
Java Basics Enhanced IO flow Note 50:io Stream practice copy multi-level folder cases