java file delete忽略错误_java file.delete 删除文件,有时候成功有时候失败,求高手解决...

主要功能是,将excel文件的数据导入到数据库成功后,见该excel文件移动到bak文件夹,同时删除原来文件夹的文件以下是代码:protectedvoidmoveFile(StringfilePath,StringfileName)thr...

主要功能是,将excel文件的数据导入到数据库成功后,见该excel文件移动到bak文件夹,同时删除原来文件夹的文件

以下是代码:

protected void moveFile(String filePath, String fileName) throws Exception

{

this.properties = new Properties();

FileInputStream fis = new FileInputStream(propertiesFilePath);

this.properties.load(fis);

//move the success upload file into bak folder

String oldDir = filePath + "\\";

String newDir = null;

boolean findbak = false;

File files = new File(filePath);

File fileArray[] = files.listFiles();

for(File file:fileArray){

if(file.isDirectory() && file.getName().equals("bak")){

newDir = filePath+"\\bak\\";

findbak = true;

break;

}

}

if(!findbak){

newDir = files.getParent()+"\\bak\\";

}

Date date = new Date();

File oldFile = new File(oldDir + fileName);

File newFile = new File(newDir + fileName.replace(".xls", "_" + DateUtil.formatDate(date, "yyyyMMddHHmmss") + ".xls"));

FileUtil.copyFile(oldFile, newFile);

//delete old file

oldFile = new File(oldDir + fileName);

System.gc();

fis.close();//new add

if (oldFile.exists())

{

boolean result = FileUtil.delete(oldFile);

if (result)

System.out.println("The file is moved to backup folder.");

else

System.out.println("The file is fail to move to backup folder.");

}

}

其中

public static void copyFile(File source, File dest) throws IOException{

if(!dest.exists()){

dest.createNewFile();

}

InputStream in = null;

OutputStream out = null;

try{

in = new FileInputStream(source);

out = new FileOutputStream(dest);

byte[] buf = new byte[1024];

int len;

while((len = in.read(buf)) > 0){

out.write(buf, 0, len);

}

}

finally{

in.close();

out.close();

}

}

public static boolean delete(File resource) throws IOException{

return resource.delete();

}

展开

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值