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);
}
}