Reputation: 596
I have a problem with that code:
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\\
}
}
}
}
How can I save files with specific name in example AAA.txt to folder1 and BBB.txt to folder 2. Thanks for any examples
Upvotes: 1
Views: 160
Reputation: 15896
From Files class from Java 7:
Use 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);
}
}
Upvotes: 2