編寫程序實現指定文件的複製粘貼

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;


public class Test9 {


/**

* 編寫程序, 將指定目錄下所有.java文件拷貝到另一個目的中,並將擴展名改爲.txt
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub


// 創建Scanner對象接收鍵盤輸入源路徑和目標路徑
Scanner scanner = new Scanner(System.in);
// 提示輸入源路徑
System.out.println("請輸入源路徑:");
String sourcePath = scanner.nextLine();
// 提示輸入目標路徑
System.out.println("請輸入目標路徑:");
String targetPath = scanner.nextLine();
// 獲取源路徑
File source = new File(sourcePath);
// 判斷源路徑是否存在,如果不存在,報錯並返回
if (!source.exists()) {
System.out.println("該源路徑不存在");
return;
}
// 獲取目標路徑
File target = new File(targetPath);
// 判斷目標路徑是否存在,如果不存在則創建該路徑
if (!target.exists()) {
target.mkdirs();
}


// 調用拷貝方法
copyAllJava(source, target);
System.out.println("拷貝成功");
}


private static void copyAllJava(File source, File target)
throws IOException {
// TODO Auto-generated method stub
// 獲取源路徑中的所有文件
File[] sourceFileList = source.listFiles();
// 遍歷所有文件
for (int i = 0; i < sourceFileList.length; i++) {
// 如果文件是*.java文件,則複製到目標路徑,並該爲*.txt文件
if (sourceFileList[i].getName().endsWith(".java")) {
File targetFile = new File(target, sourceFileList[i].getName().replace(
".java", ".txt"));
BufferedReader bufReader = null;
BufferedWriter bufWriter = null;
try {
bufReader = new BufferedReader(new FileReader(sourceFileList[i]));
bufWriter = new BufferedWriter(new FileWriter(targetFile));
String str = "";
while ((str = bufReader.readLine()) != null) {// 運用字符緩衝流,複製java文件進入目標路徑下同名txt文件.
bufWriter.write(str);
bufWriter.newLine();
}
} catch (IOException e) {
throw e;
} finally {// 關閉資源.
if (bufWriter != null)
try {
bufWriter.close();
} catch (IOException e) {
throw e;
} finally {
if (bufReader != null)
try {
bufReader.close();
} catch (IOException e) {
throw e;
}
}
}
}
// 如果文件是文件夾,則採用遞歸方法遍歷該文件夾
if (sourceFileList[i].isDirectory()) {
File targetFiles = new File(target, sourceFileList[i].getName());
targetFiles.mkdirs();
copyAllJava(sourceFileList[i], targetFiles);
}
}


}


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章