Update : Move files from one folder to another based on file extension

后端 未结 3 1258
耶瑟儿~
耶瑟儿~ 2021-01-25 12:46

Situation:

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 t

3条回答
  •  滥情空心
    2021-01-25 13:08

    Copy this class and run :) Try setting the correct source and destination path if it doesn't work.

    import java.io.File;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.nio.file.StandardCopyOption;
    
    public class MoveFile {
    
        private boolean moveFile(String source, String destination) throws IOException {
            Path srcPath = Paths.get(source);
            Path destPath = Paths.get(destination);
            System.out.println("Moving processed file to archive");
            Files.move(srcPath, destPath, StandardCopyOption.REPLACE_EXISTING);
            return true;
        }
    
        private File[] getTheFilesWithExtension(String filePath, String ext) {
    
            File fileDir = new File(filePath);
            File[] files = fileDir.listFiles((dir, name) -> name.toLowerCase().endsWith(ext));
            return files;
        }
    
        public static void main(String... args){
            {
                MoveFile moveFile = new MoveFile();
                String sourcePath = "C:\\\\Users\\\\sh370472\\\\Downloads";
                String destPath = "E:\\Query\\";
                String extension = ".csv";
                try {
                    File[] files = moveFile.getTheFilesWithExtension(sourcePath, extension);
                    for (File file : files){
                        moveFile.moveFile(file.getPath(),destPath+file.getName());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

    Note: Its for Java 8 and above , for lower java version, you can update the lambda expression in getTheFilesWithExtension with the below code

    private File[] getTheFilesWithExtension(String filePath, String ext) {
    
            File fileDir = new File(filePath);
            File[] files = fileDir.listFiles(
                    new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String name) {
                            return name.toLowerCase().endsWith(ext);
                        }
                    }
            );
            return files;
        }
    

提交回复
热议问题