Example 1: Receive a folder path from the keyboard, print all the files in the folder and the name of the folder at the level
Analysis: The method and recursion of the file class are used here
public class test10{
public static void Main (string[] args)
{
Scanner sc=new Scanner (system.in);
String Path=sc.nextline ();
File F=new file (path);
System.out.println (F.getname ());
Method (f,1);
}
public static void Method (File F, int. level)
{
File [] files=f.listfiles ();
for (File file:files)
{
for (int i=0;i<level;i++)
{
System.out.print ("\ t");
}
System.out.println (File.getname ());
if (File.isdirectory ())
{
Method (file,level+1);
}
}
}
}
Example 2: Receive two folder paths from the keyboard, copy one of the folders (containing content) to another folder
public class Test9 {
public static void Main (string[] args) throws IOException {
Scanner sc = new Scanner (system.in);
System.out.println ("Please enter source path");
String pathsrc = Sc.nextline ();
System.out.println ("Please Enter destination path");
String pathdest = Sc.nextline ();
Method (Pathsrc,pathdest);
}
public static void Method (String pathsrc,string pathdest) throws ioexception{
Encapsulates the source and gets all the file objects in the source
File F = new file (PATHSRC);
file[] files = f.listfiles ();
If the directory for the destination does not exist, create
File Filedest = new file (pathdest);
if (!filedest.exists ()) {
Filedest.mkdir ();
}
Traverse all file objects in the source
for (File file:files) {
If it is a folder, the recursion
if (File.isdirectory ()) {
The subordinate directory name is the current destination directory name plus the next folder name
Method (File.getabsolutepath (), pathdest + "\ \" + file.getname ());
}
else{
If it is a file, copy
Bufferedinputstream bis = new Bufferedinputstream (new FileInputStream (file));
Bufferedoutputstream BOS = new Bufferedoutputstream (new FileOutputStream (pathdest + "\ \" + file.getname ()));
byte[] bys = new byte[1024];
int len = 0;
while (len = Bis.read (bys))! =-1) {
Bos.write (Bys,0,len);
}
Bos.close ();
Bis.close ();
}
}
}
}