java IO 实现剪切本地文件

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


/********剪切文件**********************/


public class TestJianQie {
public static void main(String[] args) {
TestJianQie jianqie = new TestJianQie();
try {
jianqie.func();
} catch (FileNotFoundException e) {
e.printStackTrace();
}


// File f = new File("D:\\1234.txt");
// jianqie.del(f);


}


public void func() throws FileNotFoundException {
// 1.源文件
// 2.目标文件
// 3.输入流
// 4.输出流
File src = new File("D:\\test.txt");


if (!src.exists()) {
throw new FileNotFoundException("找不到文件");
}


File dest = new File("G:\\abc.txt");


if (!dest.exists()) {
try {
dest.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}


// 3.输入流
FileInputStream input = null;  // 局部变量需要   赋初始值
input = new FileInputStream(src);


// 4.输出流
FileOutputStream output = null;
output = new FileOutputStream(dest);


// 确定复制的速度
byte[] group = new byte[1024000];


int size = 0;
System.out.println("正在复制内容....");


// 开始复制
try {
while ((size = input.read(group)) != -1) {
// 边读边写
output.write(group, 0, size);
}
System.out.println("复制成功");


} catch (IOException e) {


e.printStackTrace();
} finally {
try {
if (input != null) {
input.close();
}
if (output != null) {
output.close();
}


// 删除源目录
del(src);
System.out.println("删除成功");
} catch (IOException ec) {


}
}


}


private void del(File f) {
System.out.println("正在准备删除");


if (f.isFile()) { // 是否是目录
f.delete();
} else {


File[] file = f.listFiles();


if (file == null) {
f.delete();
return;
}
for (File fm : file) {


if (fm.isFile()) {
System.out.println("即将删除文件:" + fm.getName());
fm.delete();
} else {
del(fm);
}
}
f.delete();


}
}


}

猜你喜欢

转载自blog.csdn.net/banpu/article/details/75452942