Home > Blockchain >  Fetch path of recently downloaded file
Fetch path of recently downloaded file

Time:03-08

I'm working on an automation task, where a file gets downloaded and I have to extract path of that downloaded file alongwith name (I know that file will be downloaded in Downloads folder, but I want path for the latest downloaded file only). Ultimately, I want to fetch extension. But I'll be able to fetch extension only when path is available, please help me out with extracting path.

CodePudding user response:

This should do the job:

package foo;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class Bar {

    public static File getNewestFileFromDir(File dir) throws IOException {      
        File newestFile = null;
        Date newestCreationDate = null;
        File[] files = dir.listFiles(File::isFile);
        for (File file: files) {
            Path filePath = file.toPath();
            BasicFileAttributes attributes = Files.readAttributes(filePath, BasicFileAttributes.class);
            long milliseconds = attributes.creationTime().to(TimeUnit.MILLISECONDS);
            if ((milliseconds > Long.MIN_VALUE) && (milliseconds < Long.MAX_VALUE)) {
                Date creationDate = new Date(attributes.creationTime().to(TimeUnit.MILLISECONDS));
                if (newestCreationDate != null) {
                    if (creationDate.after(newestCreationDate)) {
                        newestCreationDate = creationDate;
                        newestFile = file;
                    }
                }
            }
        }
        return newestFile;
    }
    
    public static String getFileExtension(File file) {
        String extension = "";
        String fileName = file.getName();
        int i = fileName.lastIndexOf('.');
        if (i > 0) {
            extension = fileName.substring(i   1).toLowerCase();
        }
        return extension;
    }

}
  • Related