我的代码有问题:
public class Files {
public static void main(String[] args) throws IOException {
// filter files AAA.txt and BBB.txt from another's
File f = new File("d:\\dir"); // current directory
File f1 = new File("d:\\dir1\\");
FilenameFilter textFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
if (name.startsWith("A") && name.endsWith(".TXT")) {
//System.out.println(name);
return true;
}
else if (name.startsWith("B") && name.endsWith(".TXT")) {
//System.out.println(name);
return true;
}
else {
//System.out.println(name);
return false;
}
}
};
File[] files = f.listFiles(textFilter);
for (File file : files) {
if (file.getName().startsWith("A") ) {
//here save file to d:\\folder1\\
}
}
}
}
如何将示例AAA.txt中具有特定名称的文件保存到folder1,将BBB.txt保存到文件夹2.感谢任何示例
答案 0 :(得分:2)
来自Java 7的Files类:
使用move(Path source, Path target, CopyOption... options)
import static java.nio.file.StandardCopyOption.*;
import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.nio.file.Files;
...
for (File file : files) {
if (file.getName().startsWith("A") ) {
//here save file to d:\\folder1\\
// convert file to Path object use toPath() method.
Path targetFilePath = FileSystems.getDefault().getPath("d:\\folder1\\").resolve(file.getFileName())
Files.move(file.toPath(), targetFilePath , REPLACE_EXISTING);
}
}