文件拷貝
linux下文件拷貝命令:"cp 源文件路徑 目標文件路徑
"
現在希望通過程序來實現這樣的操作,即:建立一個copyFile程序類,這個類通過初始化參數接收源文件與目標文 件路徑。
分析:
- 要想實現數據的拷貝肯定是要通過流的方式來完成,對於流有兩類,由於要拷貝的內容不一定是文字數據,所以此處我們採用字節流。
- 在進行拷貝的時候需要確定模式:a.在程序中開闢一個數組,該數組長度爲文件長度,將所有數據一次性讀取到該數組中隨後進行輸出保存。b.採用同邊讀邊寫的方式完成。
package www.bit.FileTest;
import java.io.*;
/**
* 建立一個專門負責文件拷貝處理的類,該類具備如下功能:
* 1.判斷拷貝的源文件是否存在
* 2.判斷目標文件的父路徑是否存在,如果不存在則創建父目錄
* 3.進行文件拷貝的處理
*/
class CopyFileUtil {
// 此時這個工具類不需要任何屬性,
// 建議將構造方法私有化,並且文件操作方法均爲類方法
private CopyFileUtil(){}
/**
* 判斷要拷貝的源文件路徑是否存在
* @param sourceFilePath 輸入的源路徑信息
* @return 如果該路徑真實存在返回true,否則返回false
*/
public static boolean sourceFilePathIsExists(String sourceFilePath){
return new File(sourceFilePath).exists();
}
/**
* 根據傳入的目標文件路徑判斷其父路徑是否存在,如果不存在則創建
* @param destFilePath 輸出的目標文件地址,根據此地址判斷父路徑是否存在。不存在則創建
*/
public static void destFilePathExists(String destFilePath){
File file = new File(destFilePath);
if (!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
}
/**
* 文件拷貝
* @param sourceFilePath 源文件絕對路徑
* @param destFilePath 目標文件絕對路徑
* @return 是否拷貝成功
* @throws Exception
*/
public static boolean copyFile(String sourceFilePath,String destFilePath) throws Exception{
File sourceFile = new File(sourceFilePath);
File destFile = new File(destFilePath);
InputStream inputStream = new FileInputStream(sourceFile);
OutputStream outputStream = new FileOutputStream(destFile);
long startTime = System.currentTimeMillis();
copyFileHandle(inputStream,outputStream);
long endTime = System.currentTimeMillis();
System.out.println("文件拷貝結束,共耗時" + (endTime-startTime) + "毫秒");
return true;
}
/**
* 實現具體的文件拷貝操作
* @param inputStream 輸入流對象
* @param outputStream 輸出流對象
* @throws Exception
*/
private static void copyFileHandle(InputStream inputStream,
OutputStream outputStream)throws Exception{
int len = 0;
byte[] data = new byte[1024]; // 開闢緩衝區一次性讀入多個內容
while ((len = inputStream.read(data)) != -1){ // 表示將數據讀取到字節數組之中,而後返回讀取個數
outputStream.write(data,0,len); // 將字節數組的部分內容寫到目標文件中
}
inputStream.close();
outputStream.close();
}
}
public class CopyFile {
public static void main(String[] args) throws Exception {
if (args.length != 2){
System.out.println("非法操作,命令爲: java CopyFile 源文件路徑 目標文件路徑");
return;
}
String sourceFilePath = args[0]; // 取得源文件路徑
String destFilePath = args[1]; // 取得目標路徑
if (CopyFileUtil.sourceFilePathIsExists(sourceFilePath)){
CopyFileUtil.destFilePathExists(destFilePath);
System.out.println(CopyFileUtil.copyFile(sourceFilePath,destFilePath)
? "文件拷貝成功" : "文件拷貝失敗");
}else {
System.out.println("源文件不存在,無法進行拷貝");
}
}
}