你下面这段代码有误,renameTo(...)方法并不是剪切文件,而是重命名文件
//如果源目录是一个文件就直接剪切
if (file1.isFile())
{
file1.renameTo(file2);
}
下面是我实现文件夹剪切功能的一个例子,虽然并不完善,但是也实现了剪切的功能:- package file;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- /**
- * 一个实现文件夹剪切功能的程序
- * @author Chu
- *
- */
- public class MoveFile {
- private static String srcDir;
- private static String desDir;
- static int length;
-
- public static void main(String[] args) throws Exception {
- //确定文件夹的源目录和目的目录
- srcDir = "D:\\123";
- desDir = "H:\\111";
- length = new File(srcDir).getParentFile().getAbsolutePath().length();
- moveFile(srcDir, desDir);
-
- System.out.println("move success");
- }
-
- //实现剪切功能的方法
- public static void moveFile(String src, String des) throws Exception {
- //将源目录和目的目录封装成文件对象
- File srcFile = new File(src);
- cut(srcFile, des);
- }
- //剪切文件夹
- private static void cut(File srcFile, String desFile) throws Exception {
- // TODO Auto-generated method stub
- //如果源目录是一个文件夹,则遍历内部文件
- if (srcFile.isDirectory()) {
- //文件夹路径
- String srcPath = srcFile.getAbsolutePath();
- String desPath = desFile+srcPath.substring(length-1);
- //desPath = desPath.replaceAll("\\\\", "\\\\\\\\");
- File f = new File(desPath);
- f.mkdir(); //创建目录
-
- File[] files = srcFile.listFiles();
- for (File file : files){
- //递归调用moveFile方法
- moveFile(file.getPath(), desFile);
- }
- srcFile.delete(); //删除原文件目录文件夹
- }else{
- copyFile(srcFile, desFile);
- }
- }
- //复制文件
- private static void copyFile(File srcFile, String desFile) throws Exception {
- // TODO Auto-generated method stub
- InputStreamReader isr = new InputStreamReader(new FileInputStream(srcFile), "UTF-8") ;
-
- String srcPath = srcFile.getParentFile().getAbsolutePath();
- String desPath = desFile+srcPath.substring(length-1)+"\\"+srcFile.getName();
-
- desPath = desPath.replaceAll("\\\\", "\\\\\\\\");
- OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(desPath), "UTF-8") ;
-
- BufferedReader br = new BufferedReader(isr);
- BufferedWriter bw = new BufferedWriter(osw);
-
- String line = null;
- while((line=br.readLine())!=null)
- {
- bw.write(line);
- bw.newLine(); //换行
- bw.flush(); //刷新缓冲区
- }
-
- try {
- if(bw!=null)
- bw.close(); //关闭缓冲区,也就是关闭流
- if(br!=null)
- br.close(); //关闭缓冲区
- } catch (IOException e) {
- System.out.println(e.toString());
- }
- srcFile.delete(); //复制完后删除源文件
- }
- }
复制代码 |