java 文件目录操作_Java目录文件的操作 -解道Jdon

目录文件的操作

目录文件的操作也是除了数据库操作以外,经常需要操作的一个数据对象.

移动文件,相当于linux 中mv命令,但与平台无关:

/**

* This class moves an input file to output file

*

* @param String input file to move from

* @param String output file

*

*/

public static void move (String input, String output){

File inputFile = new File(input);

File outputFile = new File(output);

inputFile.renameTo(outputFile);

}

拷贝文件,相当于linux中cp命令,但与平台无关,可以拷贝文本 或二进制文件:

/**

* This class copies an input file to output file

*

* @param String input file to copy from

* @param String output file

*/

public static boolean copy(String input, String output) throws Exception{

int BUFSIZE = 65536;

try{

FileInputStream fis = new FileInputStream(input);

FileOutputStream fos = new FileOutputStream(output);

int s;

byte[] buf = new byte[BUFSIZE];

while ((s = fis.read(buf)) > -1 ){

fos.write(buf, 0, s);

}

}catch (Exception ex) {

throw new Exception("makehome"+ex.getMessage());

}

return true;

}

拷贝目录,下例只可以拷贝目录中的文件:

/**

* This class copies an input files of a directory to another directory

not include subdir

*

* @param String sourcedir the directory to copy from such as:/home/bqlr/images

* @param String destdir the target directory

*/

public static void CopyDir(String sourcedir,String destdir) throws Exception

{

File dest = new File(destdir);

File source = new File(sourcedir);

String [] files= source.list();

try

{

destdir.mkdirs();

}catch (Exception ex) {

throw new Exception("CopyDir:"+ex.getMessage());

}

for (int i = 0; i < files.length; i++)

{

String sourcefile = source+File.separator+files[i];

String destfile = dest+File.separator+files[i];

File temp = new File(sourcefile);

if (temp.isFile()){

try{

copy(sourcefile,destfile);

}catch (Exception ex) {

throw new Exception("CopyDir:"+ex.getMessage());

}

}

}

}

删除目录.包括目录下所有文件和目录:

/**

* This class del a directory recursively,that means delete all files

and directorys.

*

* @param File directory the directory that will be deleted.

*/

public static void recursiveRemoveDir(File directory) throws Exception

{

if (!directory.exists())

throw new IOException(directory.toString()+" do not exist!");

String[] filelist = directory.list();

File tmpFile = null;

for (int i = 0; i < filelist.length; i++) {

tmpFile = new File(directory.getAbsolutePath(),filelist[i]);

if (tmpFile.isDirectory()) {

recursiveRemoveDir(tmpFile);

} else if (tmpFile.isFile()) {

tmpFile.delete();

}

}

directory.delete();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值