Java基礎IO檔案拷貝練習題,javaio拷貝練習題
/**
* 編寫一個程式,把指定目錄下的所有的帶.java檔案都拷貝到另一個目錄中,拷貝成功後,把尾碼名是.java的改成.txt。
*/
1.我們看到這個題還是用大化小的思想來做
分析:1.拷貝 >>> 選擇什麼流呢??>>>拷貝我在上篇部落格中寫到,我們用位元組流,字元流唯讀唯寫
2.java結尾 >> 我們可以想到String中的endsWith()方法.
3.拷貝成功後再改尾碼名>>File中有一個尾碼名的方法renameTo()的方法
4.如果就收拷貝的檔案的檔案夾中有相同的名字的檔案怎麼辦呢?? 想想這個
我們看代碼:第一步:1.拷貝 >>> 選擇什麼流呢??>>>拷貝我在上篇部落格中寫到,我們用位元組流,字元流唯讀唯寫
2.java結尾 >> 我們可以想到String中的endsWith()方法.
/* *檔案的拷貝 */ private static void copy(File src, File dest) throws IOException { File[] files = src.listFiles(); //判斷數組是否為空白 if (files != null) { //遍曆數組 for (File file : files) { //是檔案並且以java結尾的檔案 if (file.isFile() && file.getName().endsWith(".java")) { //緩衝流拷貝 速度快 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(new File(dest, file.getName()))); byte[] by = new byte[1024]; int len = 0; while ((len = bis.read(by)) != -1) { bos.write(by, 0, len); } //關流 bos.close(); bis.close(); //如果是檔案 } else if (file.isDirectory()) { //在判斷這個檔案夾是不是空的或者沒有java檔案 那樣我們就不要複製了 定義remove() if (remove(file)) { File newfile = new File(dest, file.getName()); newfile.mkdirs(); copy(file, newfile); } } } } } private static boolean remove(File file) { File[] files = file.listFiles(); //判斷數組是否為空白 if (file != null) { for (File file2 : files) { //是檔案並且以java結尾的檔案 返回真 if (file2.isFile() && file2.getName().endsWith(".java")) { return true; //這裡是關鍵 不經要是檔案 而且還要滿足檔案中要包含java檔案 } else if (file2.isDirectory() && remove(file2)) { return true; } } } //條件不符合返回false return false; }}
第二步:3.拷貝成功後再改尾碼名>>File中有一個尾碼名的方法renameTo()的方法
4.如果就收拷貝的檔案的檔案夾中有相同的名字的檔案怎麼辦呢?? 想想這個
//.java修改成.txt private static void revamp(File dest) throws IOException{ File[] file = dest.listFiles(); for (File file2 : file) { if(file2.isFile()){ //擷取檔案名稱字串 String sb = file2.getName(); //判斷是否是Java檔案 if(sb.endsWith(".java")){ StringBuilder sb1 = new StringBuilder(sb); //替換 把java字串 替換成.txt字串 sb1.replace(sb1.toString().indexOf(".java"), sb1.length(), ".txt"); //建立檔案 File newfile = new File(dest, sb1.toString()); //再來一次迴圈 迴圈本次數組中的檔案和檔案夾 for (File file3 : file) { //如果裡面有相同的檔案的就刪除在 重新命名 if(file3.isFile() && newfile.getName().equals(file3.getName())){ file3.delete(); } } //判斷檔案夾中是否存在重名 file2.renameTo(newfile); } //如果是檔案 就遞迴 } else if (file2.isDirectory()) { revamp(file2); } } }
main方法
public static void main(String[] args) throws IOException { //封裝檔案地址 File src = new File("E:\\IO流"); File dest = new File("E:\\IO"); //拷貝 copy(src, dest); //重新命名 revamp(dest); }