File Download

Set the Download Folder

Path downloads = Path.of("target", "downloads").toAbsolutePath();
Files.createDirectories(downloads);

ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", Map.of(
        "download.default_directory", downloads.toString(),
        "download.prompt_for_download", false,
        "plugins.always_open_pdf_externally", true));   // download PDFs instead of opening the viewer
WebDriver driver = new ChromeDriver(options);

Wait for the File

driver.findElement(By.linkText("Download invoice")).click();
Path invoice = downloads.resolve("invoice-ORD-1002.pdf");
new WebDriverWait(driver, Duration.ofSeconds(20))
        .until(d -> Files.exists(invoice) && !Files.exists(downloads.resolve("invoice-ORD-1002.pdf.crdownload")));
System.out.println("Downloaded " + invoice.getFileName() + ", " + Files.size(invoice) + " bytes");

Example

Output:

Run InvoiceDownloadTest.main()

Example output

Downloaded invoice-ORD-1002.pdf, 48213 bytes

Tip: Chrome writes .crdownload while downloading. Wait until that temporary file is gone before reading the PDF.

Checking a Downloaded File

Example

After the download, the check is plain file handling. This example creates a CSV in a temp folder (standing in for a downloaded order report), checks it and deletes it:

import java.nio.file.*;
import java.util.List;

public class Main {
    public static void main(String[] args) throws Exception {
        Path dir = Files.createTempDirectory("downloads");
        Path report = dir.resolve("orders-report.csv");
        Files.writeString(report, "order,amount\nORD-1001,1299\nORD-1002,2450\n");

        List<String> lines = Files.readAllLines(report);
        System.out.println("File exists: " + Files.exists(report));
        System.out.println("Name ends with .csv: " + report.getFileName().toString().endsWith(".csv"));
        System.out.println("Header: " + lines.get(0) + ", data rows: " + (lines.size() - 1));

        Files.delete(report);
        Files.delete(dir);
        System.out.println("Cleaned up: " + !Files.exists(dir));
    }
}

Output

File exists: true
Name ends with .csv: true
Header: order,amount, data rows: 2
Cleaned up: true