只是簡單地寫了兩個函數,第一個函數是將一個文件從oldpath copy到newpath.
拷貝文件夾調用了拷貝文件的方法,將文件夾中的每一個文件依次拷貝過去,具體的代碼如下:
從下面的代碼中也能看出,我沒有使用遞歸方法拷貝文件夾包含文件夾的情況,如果有需要,只需稍微修改代碼即可。
public void copyFile(String strOldpath,String strNewPath)
{
try
{
File fOldFile = new File(strOldpath);
if (fOldFile.exists())
{
int bytesum = 0;
int byteread = 0;
InputStream inputStream = new FileInputStream(fOldFile);
FileOutputStream fileOutputStream = new FileOutputStream(strNewPath);
byte[] buffer = new byte[1444];
while ( (byteread = inputStream.read(buffer)) != -1)
{
bytesum += byteread; //這一行是記錄文件大小的,可以刪去
fileOutputStream.write(buffer, 0, byteread);//三個參數,第一個參數是寫的內容,
//第二個參數是從什麼地方開始寫,第三個參數是需要寫的大小
}
inputStream.close();
fileOutputStream.close();
}
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("複製單個文件出錯");
e.printStackTrace();
}
}
public void copyFolder(String strPatientImageOldPath,String strPatientImageNewPath)
{
File fOldFolder = new File(strPatientImageOldPath);//舊文件夾
try
{
File fNewFolder = new File(strPatientImageNewPath);//新文件夾
if (!fNewFolder.exists())
{
fNewFolder.mkdirs();//不存在就創建一個文件夾
}
File [] arrFiles = fOldFolder.listFiles();//獲取舊文件夾裏面所有的文件
for (int i = 0; i < arrFiles.length; i++)
{
//從原來的路徑拷貝到現在的路徑,拷貝一個文件
if (!arrFiles[i].isDirectory())
{
copyFile(strPatientImageOldPath+"/"+arrFiles[i].getName(), strPatientImageNewPath+"/"+arrFiles[i].getName());
}
}
}
catch (Exception e)
{
// TODO: handle exception
}
}