我正在使用Spring Batch来处理我正在进行的项目,并且我能够成功地将文件移动到一个新文件中,但我也在努力重命名这个文件。这是我的配置:
<j:step id="moveProcessedFile">
<j:tasklet ref="processedFileMove" allow-start-if-complete="true" />
</j:step>
<bean id="processedFileMove" class="com.ussco.wms.batch.wmcstint.MoveFileTasklet">
<property name="targetObject">
<bean class="JdkFileHandler" />
</property>
<property name="targetMethod" value="moveFile" />
<property name="arguments">
<list>
<value>${ipfile}</value>
<value>${ipfile.folder}</value>
</list>
</property>
</bean>
这是MoveFileTasklet。它与MethodInvokingTaskletAdapter:
几乎相同public class MoveFileTasklet extends AbstractMethodInvokingDelegator<Object> implements Tasklet{
private static Logger log = LoggerFactory.getLogger(MoveFileTasklet.class);
//Create method for date and time rename within Tasklet. Implement execute as well
public boolean renameFile(File fileName){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
log.info("test");
return false;
}
/**
* Following methods directly copied from MethodInvokingTaskletAdapter
*/
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
contribution.setExitStatus(mapResult(invokeDelegateMethod()));
return RepeatStatus.FINISHED;
}
protected ExitStatus mapResult(Object result) {
if (result instanceof ExitStatus) {
return (ExitStatus) result;
}
return ExitStatus.COMPLETED;
}
}
其中JdkFileHandler的方法为moveFile
:
public boolean moveFile(File fileToMove, String targetDirectory) throws IOException {
return renameFile(fileToMove, new File(targetDirectory + FILE_SEPARATOR + fileToMove.getName()));
}
和renameFile:
private boolean renameFile(File fileToRename, File renamedTargetFile) throws IOException {
if (!fileToRename.exists()) {
throw new FileNotFoundException(fileToRename + " does not exist.");
} else if (!fileToRename.isFile()) {
throw new IOException(fileToRename + " is not a file and cannot be remaned.");
} else if (renamedTargetFile.exists()) {
throw new IOException(renamedTargetFile + " already exists so the file " + fileToRename
+ " cannot be renamed to it.");
}
return fileToRename.renameTo(renamedTargetFile);
}
现在我可以将文件移动到正确的位置,但我需要将文件重命名为fileNamemmddyyhhmmss
此外,我无法更改JdkFileHandler中的任何方法。我想在我指定的MoveFileTasklet
或其他方式中实现我自己的方法。
我知道这些信息到处都是。我不是在寻找如何做的代码,我应该如何继续。现在有点卡住了。有什么建议吗?
答案 0 :(得分:1)
发布移动存档的当前实现并将当前时间附加到文件名。
public static void moveArchive(File file, String initDirectory, String destDirectory) {
File finalArchive;
File initialArchive = new File(initDirectory + file.getName());
finalArchive = new File(destDirectory + file.getName() + "." + getCurrentDate("yyyyMMddHHmmss"));
if (!initialArchive.renameTo(finalArchive)) {
log.error("Couldn't move the file.");
}
}
public static String getCurrentDate(String format) {
String dtStr = "";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date dt1 = new Date();
dtStr = sdf.format(dt1);
return dtStr;
}