Java簡單實現檔案剪下的功能
阿新 • • 發佈:2019-02-10
package 檔案剪下; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class Cut { public static void cutfile(String source,String destiny) throws IOException{ FileInputStream f_in = null; FileOutputStream f_out = null; int s_mid = source.lastIndexOf("/"); String s_last = source.substring(s_mid+1);//檔案的名字和型別 取出 x.txt String end = destiny +"/" +s_last ;// 新檔案 = destiny(c:/1/3/a)+"/" + x.txt String s_before = source.substring(0, s_mid);//原始檔的 資料夾 _取出c:/a/b/c 從 c:/a/b/c/1.txt File temp = new File(end); //為了測試 2 判斷目標資料夾 是否有同名檔案 File check = new File(source); if(check.exists()) { if(destiny.equals(s_before))// 1.原位置 剪下 不執行任何操作 { System.out.println("目標資料夾和原始檔夾相同!\n剪下已完畢"); }else if(temp.exists())// 2. 目的_資料夾中 已經存在同名的檔案,則剪下成帶標記的新檔案 { System.out.println("目標資料夾已經存在相同檔名 的檔案"); end = destiny+"/(剪下)"+s_last; try { f_in = new FileInputStream(source); f_out = new FileOutputStream(end); byte[] b = new byte[2048]; int length = f_in.read(b); while(length > 0){ f_out.write(b, 0, length); length = f_in.read(b); } } catch (FileNotFoundException e) { e.printStackTrace(); }finally{ f_in.close(); f_out.close(); } File del = new File(source); del.delete(); System.out.println("剪下已完成"); } else { File path = new File(destiny); if(!path.exists()){ System.out.println("你輸入的目的資料夾不存在,已為你自動建立資料夾!"); path.mkdirs(); } try { f_in = new FileInputStream(source); f_out = new FileOutputStream(end); byte[] b = new byte[2048]; int length = f_in.read(b); while(length > 0){ f_out.write(b, 0, length); length = f_in.read(b); } } catch (FileNotFoundException e) { e.printStackTrace(); }finally{ f_in.close(); f_out.close(); } File del = new File(source); del.delete(); System.out.println("剪下已完成"); } } else{System.out.println("原始檔不存在"); return; } } }
Cut
{
if 判斷原始檔是否存在,存在則執行下面的
{
考慮 if 1.目標資料夾 和 原始檔資料夾 相同
{
什麼也不做
}
else if 2.目標資料夾中 已經存在 和 原始檔 *名字相同* 的檔案
{
目標檔案的名字 加上 (剪下)
}
else 3.目標資料夾 不存在
{
新建目標資料夾
}
}else 原始檔不存存在
}
package 檔案剪下; import java.io.IOException; import java.util.Scanner; public class TestCut { public static void main(String[] args) throws IOException { System.out.println("請輸入要剪下的原始檔的地址,如:d:/abc/as/xxx.txt"); Scanner in = new Scanner(System.in); String str_s = in.next(); System.out.println("請輸入目的地址,如: d:/abc/as 或者 c: "); String str_d = in.next(); Cut.cutfile(str_s,str_d); } }