Two methods:
1. Copy all files and folders under a directory
2. Merge all text files in one file directory into the same file
Copy Code code as follows:
Package com.firewolf.test;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
public class Filereaderutil {
public static void Main (string[] args) {
try {
Mergefile (New file ("C:/Documents and settings/liuxing0/Desktop/new Folder/script"), New file ("D:/all.sql"));
CopyFiles (New file ("g:/Learning materials/Notes"), New file ("G:/test");
catch (IOException e) {
E.printstacktrace ();
}
}
/**
* Copy all files in a file directory,
* @param sourcepath Original file directory
* @param despath Destination file directory
*/
private static void CopyFiles (File sourcefile,file desfile) throws ioexception{
if (Sourcefile.isfile ()) {
File File = new file (Desfile.getpath () + "/" +sourcefile.getname ());
FileInputStream fis = new FileInputStream (sourcefile);
FileOutputStream fos = new FileOutputStream (file);
int len = 0;
byte[] buf = new byte[1024];
while (len = Fis.read (buf))!=-1)
Fos.write (Buf,0,len);
}else{
File dir = new file (Desfile.getpath () + "/" +sourcefile.getname ());
if (!dir.exists ())
Dir.mkdir ();
string[] names = Sourcefile.list ();
for (int i = 0; i < names.length; i++) {
CopyFiles (New File (Sourcefile.getpath () + "/" +names[i]), dir);
}
}
}
/**
* A method (mainly used to merge many text files together) in a single file of all files below a file directory
* @param sourcefile
* @param decfile
* @return
* @throws IOException
*/
private static file Mergefile (file Sourcefile,file decfile) throws ioexception{
string[] filelist = Sourcefile.list ();
for (String string:filelist) {
File File = new file (Sourcefile.getpath () + "/" +string);
if (!file.isdirectory ()) {
FileInputStream fis = new FileInputStream (file);
FileOutputStream fos = new FileOutputStream (Decfile, true);
byte[] buffer = new byte[1024];
int len = 0;
while ((len= fis.read (buffer)!=-1)
Fos.write (buffer, 0, Len);
}
else {
Decfile = Mergefile (file,decfile);
}
}
return decfile;
}
}