更新:根据文件扩展名将文件从一个文件夹移动到另一个文件夹 [英] Update : Move files from one folder to another based on file extension
问题描述
情况:
我正在做一个自动化,我必须从一组文件中仅下载CSV文件.现在我只想将CSV文件从一个文件夹移动到另一个文件夹.
I am doing an automation where I have to download only CSV files from a set of files. And now i want to move only CSV files from one folder to another.
问题:
能否请您提供代码,以便在文件移动后立即从源文件夹中删除文件?
Can you please provide me code to delete files from the source folder as soon as the files are moved?
到目前为止,这是我的代码:
This is my code so far:
public class MyFilteredFileList {
public static void main(String a[])
{
try {
File source = new File("C:\\Users\\sh370472\\Downloads");
File dest = new File("E:\\Query\\");
FileUtils.copyDirectory(source, dest, new FileFilter() {
@Override
public boolean accept(File pathname)
{
boolean source=pathname.getName().toLowerCase().endsWith(".csv");
if (source)
return true;
return false;
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
但是我仍然面临一个问题.它会一次下载所有文件,然后删除.但是我的要求是这样的-它应该下载第一个文件->将下载的文件移到另一个文件夹中->从下载文件夹中删除第一个下载的文件->下载第二个文件夹...然后重复该过程
Edit : But I am still facing a problem. It's downloading all the files at once and then deleting. But my requirement is something like - It should download first file -> move the downloaded file into another folder -> delete first downloaded file from download folder -> download second folder... and the process repeats
推荐答案
只需添加pathname.deleteOnExit();在接受方法上
Just add pathname.deleteOnExit(); on accept method
@Override
public boolean accept(File pathname) {
boolean source = pathname.getName().toLowerCase().endsWith(".csv");
if (source) {
pathname.deleteOnExit();
return true;
}
return false;
}
整个代码:
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
/**
* Created by Lenovo on 02/12/2018.
*/
public class FileMove {
public static void main(String a[])
{
try {
File source = new File("C:\\Users\\sh370472\\Downloads");
File dest = new File("E:\\Query\\");
FileUtils.copyDirectory(source, dest, new FileFilter() {
@Override
public boolean accept(File pathname) {
boolean source = pathname.getName().toLowerCase().endsWith(".csv");
if (source) {
pathname.deleteOnExit();
return true;
}
return false;
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
这篇关于更新:根据文件扩展名将文件从一个文件夹移动到另一个文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!