主要功能是,将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();
}
展开