2023年12月1日发(作者:)

【简介】⽂件移动三种⽅法

【简介】⽂件移动三种⽅法:

1. File类中的renameTo⽅法移动⽂件,将源⽂件重新命名为另⼀个抽象路径名时能起到移动⽂件的⽬的.

Jdk 1.5 File#renameTo 写道

renameTo

* All rights reserved.

* Author: Jarg Yee

* /

*/

import static ;

import .*;

/*

* ⽂件移动三种⽅法 简介

*/

public class MoveFile

{

private static final String srcPath = "C:src"; // 源⽬录

private static final String destPath = "C:dest"; // ⽬的⽬录

private static final String fileName = ""; // ⽂件名

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(To(destFile))

n("success move(renameToMethod):" + fileName);

else

n("fail move(renameToMethod):" + fileName);

}

/** 使⽤dos命令移动⽂件 */

public static void dosMethod()

{

/** 返回与当前 Java 应⽤程序相关的运⾏时对象 */

Runtime rt = time();

/** ⽂件移动命令 */

int byteNum = 0; // 读取的字节数

try

{

in = new FileInputStream(srcFile); // ⽂件输⼊

out = new FileOutputStream(destFile); // ⽂件输出

}

catch (FileNotFoundException e)

{

n("error:" + e);

}

try

{

/**

read(buf): ⼀次最多读取长度的数据

返回实际读取字节数