我正在尝试使用 java 将上次修改的文件的内容从一个文件夹复制到另一个文件夹
我可以移动文件,但无法移动文件内容
private File getLatestFilefromDir(String dirPath) throws IOException{
File dir = new File(dirPath);
File[] files = dir.listFiles();
if (files == null || files.length == 0) {
return null;
}
File lastModifiedFile = files[0];
for (int i = 1; i < files.length; i++) {
if (lastModifiedFile.lastModified() < files[i].lastModified()) {
lastModifiedFile = files[i];
}
}
String newFilePath = "C:\\newPath\\"+lastModifiedFile.getName();
Path temp = Files.move
(Paths.get(dirPath),
Paths.get(newFilePath ));
if(temp != null)
{
System.out.println("File renamed and moved successfully");
}
else
{
System.out.println("Failed to move the file");
}
return new File(newFilePath );
}
结果:只有文件在移动,但内容没有移动
最佳答案
而是使用Apache Commons IO图书馆,更具体地说org.apache.commons.io.FileUtils 。这是一个非常好的库,非常适合您想要做的事情。
File sourceFile = new File(...);
File destinationFile = new File(...);
FileUtils.moveFile(sourceFile, destinationFile);
在我不久前做的一个小项目中非常成功地使用了它( FilingAssistant )
关于java - 如何使用java将最后修改的文件的内容从一个文件夹复制到另一个文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58166035/