我尝试删除位于Desktop/outputs/
public class FileDeleteTasklet implements Tasklet,InitializingBean {
@Value("${fileName}")
private String fileName;
@Value("home/xxx/Desktop/outputs/")
private Resource directory;
@Override
public RepeatStatus execute(StepContribution sc, ChunkContext cc) throws Exception {
String file = fileName+ time()+".csv";
try {
File dir = directory.getFile();
Assert.state(dir.isDirectory());
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].getName().equalsIgnoreCase(file)) {
boolean rename = files[i].delete();
if (!rename) {
System.out.println("Could not delete");
throw new UnexpectedJobExecutionException("Could not delete file " + files[i].getPath());
} else {
System.out.println(files[i].getPath() + " is deleted!");
break;
}
}
}
return RepeatStatus.FINISHED;
} catch (Exception ex) {
System.out.println("=========== Could not delete file " + file+ " *** failed *** due to " + ex.getMessage());
}
return RepeatStatus.FINISHED;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(directory, "directory must be set");
}
}
错误
=========== Could not delete file Reporting_2018-02-22.csv *** failed *** due to [Assertion failed] - this state invariant must be true
我在Java中意识到Assert.state deprecated
?这是错误发生的原因吗?
答案 0 :(得分:1)
isDirectory()
的文档说
当且仅当此抽象路径名表示的文件存在并且是目录时才为true;否则是假的
所以我假设该文件夹不存在。
断言失败与弃用无关 看一下SpringBoot5的javadoc,它说:
已过时。从4.3.7开始,支持state(boolean,String)
答案 1 :(得分:0)
不,这不是错误发生的原因。发生错误是因为它不是一个目录,就像代码所说的那样。
但是你不需要断言(它本来就不应该是断言,因为它不是代码的不变量),或者是无意义和浪费的目录搜索。只需使用
boolean deleted = new File(file).delete();
假设您可以控制案例问题,您应该可以这样做。