1. Copying single-level folders
Data Source: E:\\demo
Destination: E:\\test
Analysis:
A : Package Directory
B : Gets the file array of all the text under this directory
C : iterates through the file array to get each file object
D : Copy the file
2. code example:
1 Packagecn.itcast_03;2 3 ImportJava.io.BufferedInputStream;4 ImportJava.io.BufferedOutputStream;5 ImportJava.io.File;6 ImportJava.io.FileInputStream;7 ImportJava.io.FileOutputStream;8 Importjava.io.IOException;9 Ten /* One * Requirements: Copy a single-pole folder A * - * Data Source: E:\\demo - * Destination: E:\\test the * - * Analysis: - * A: Package directory - * B: Gets the file array of all the text in this directory + * C: Traverse the file array to get each file object - * D: Copy the file + */ A Public classCopyfolderdemo { at Public Static voidMain (string[] args)throwsIOException { - //Package Catalog -File Srcfolder =NewFile ("E:\\demo"); - //Package Destination -File Destfolder =NewFile ("E:\\test"); - //If the destination folder does not exist, create in if(!destfolder.exists ()) { - Destfolder.mkdir (); to } + - //gets the file array of all the text under this directory thefile[] Filearray =srcfolder.listfiles (); * $ //iterate over the file array to get each file objectPanax Notoginseng for(File file:filearray) { - //System.out.println (file); the //data Source: E:\\demo\\e.mp3 + //Destination: E:\\test\\e.mp3 AString name = File.getname ();//E.mp3 theFile NewFile =NewFile (Destfolder, name);//E:\\test\\e.mp3 + - copyFile (file, newFile); $ } $ } - - Private Static voidCopyFile (file file, file NewFile)throwsIOException { theBufferedinputstream bis =NewBufferedinputstream (NewFileInputStream ( - file));WuyiBufferedoutputstream BOS =NewBufferedoutputstream ( the NewFileOutputStream (NewFile)); - Wu byte[] Bys =New byte[1024]; - intLen = 0; About while(len = Bis.read (bys))! =-1) { $Bos.write (bys, 0, Len); - } - - bos.close (); A bis.close (); + } the}
Java Fundamentals Enhanced IO flow Note 48:io Stream practice copy single-level folder case