【简介】文件移动三种方法:
1. File类中的renameTo方法移动文件,将源文件重新命名为另一个抽象路径名时能起到移动文件的目的.
2. Runtime.getRuntime()获取与当前 Java 应用程序相关的 Runtime
对象,通过调用
public Process exec(String command)
执行dos命令移动文件.参数: cmd /c move 文件绝对路径1 文件绝对路径2
其中, /c 参数表示: 执行字符串指定的命令然后终断.
/k 参数表示: 执行字符串指定的命令然后保留.
缺少参数 /c 或 /k 都不能执行doc移动文件命令.
3. 通过文件输入输出字节流拷贝源文件到目的文件夹,后通过File类delete()方法删除源文件.
只是简单介绍能达成目的这三种方法,实现程序并没有做很好的容错处理.一些细节并没有考虑上去.
测试程序前提条件:
1. c盘根目录存在src文件夹.
2. c盘根目录存在dest文件夹.
3. 上述src文件夹下存在text.txt文件.
实现程序:
/** * Copyright (c) 2011 Trusted Software and Mobile Computing(TSMC) * All rights reserved. * Author: Jarg Yee <[email protected]> * http://jarg.iteye.com/ */ import static java.lang.System.out; import java.io.*; /* * 文件移动三种方法 简介 */ public class MoveFile { private static final String srcPath = "C:\\src\\"; // 源目录 private static final String destPath = "C:\\dest\\"; // 目的目录 private static final String fileName = "text.txt"; // 文件名 private static final File srcFile = new File(srcPath + fileName); // 源文件 private static final File destFile = new File(destPath + fileName); // 目的文件 /** for debugging. */ public static void main(String[] args) { //renameToMethod(); // 通过File类中的renameTo方法移动文件 dosMethod(); // 通过执行dos命令移动文件 //fileHandle(); // 通过字节流方式复制文件,后删除文件 } /** 通过renameTo移动文件 */ public static void renameToMethod() { if(srcFile.renameTo(destFile)) out.println("success move(renameToMethod):" + fileName); else out.println("fail move(renameToMethod):" + fileName); } /** 使用dos命令移动文件 */ public static void dosMethod() { /** 返回与当前 Java 应用程序相关的运行时对象 */ Runtime rt = Runtime.getRuntime(); /** 文件移动命令 */ String command = "cmd /c move " + srcFile + " " + destFile; /** 执行文件移动命令 */ try { Process process = rt.exec(command); } catch (Exception e) { out.println("error:" + e); } } /** 通过对文件复制与删除操作完成 由于,文件可能是流文件,应当用字节流方法复制 */ public static void fileHandle() { FileInputStream in = null; FileOutputStream out = null; byte[] buf = new byte[256]; int byteNum = 0; // 读取的字节数 try { in = new FileInputStream(srcFile); // 文件输入 out = new FileOutputStream(destFile); // 文件输出 } catch (FileNotFoundException e) { System.out.println("error:" + e); } try { /** read(buf): 一次最多读取buf.length长度的数据 返回实际读取字节数 */ while((byteNum=in.read(buf))!=-1) { // 文件字节流读到最后不一定够256个字节 out.write(buf,0,byteNum); } in.close(); out.close(); // 关闭文件输入,输出 System.out.println(srcFile.delete()); // 删除源文件 } catch (IOException e) { System.out.println("error2:" + e); } } }