You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

等待文件下载到指定文件夹并读取动态PDF,getAbsolutePath报错如何解决?

错误原因

你在isFileDownloaded方法中错误地对字符串类型变量调用了File类的专属方法:

  • 你通过file.getName()获取到的fileName是纯字符串类型,仅存储文件名文本,没有文件路径相关的方法
  • getAbsolutePath()是java.io.File类的成员方法,只能通过File类的实例调用
修复步骤
  1. 修正isFileDownloaded方法的路径赋值逻辑
    将原代码中
filePath = fileName.getAbsolutePath();

修改为

filePath = file.getAbsolutePath();

直接使用循环中遍历到的File类型对象file调用方法,即可正确获取文件的绝对路径。

  1. 修复readPdfContent方法的文件初始化逻辑
    原方法中System.getProperty(fileName)写法错误,你传入的fileName已经是完整的绝对路径,无需读取系统属性,直接作为参数构造File对象即可:
File file = new File(fileName);
修正后完整代码

1. isFileDownloaded方法

public static String isFileDownloaded(String fileText, String fileExtension, int timeOut) {
    String folderName = System.getProperty("user.dir")+"\\src\\test\\resources\\Download\\";
    File[] listOfFiles;
    int waitTillSeconds = timeOut;
    boolean fileDownloaded = false;
    String filePath = null; 

    long waitTillTime = Instant.now().getEpochSecond() + waitTillSeconds;
    while (Instant.now().getEpochSecond() < waitTillTime) {
        listOfFiles = new File(folderName).listFiles();
        for (File file : listOfFiles) {
            String fileName = file.getName().toLowerCase();
            if (fileName.contains(fileText.toLowerCase()) && fileName.contains(fileExtension.toLowerCase())) {
                fileDownloaded = true;
                filePath = file.getAbsolutePath();
                break;
            }
        }
        if (fileDownloaded) {
            break;
        }
    }
    return filePath;
}

2. readPdfContent方法

public static String readPdfContent(String fileName) throws IOException {
    File file = new File(fileName);
    PDDocument doc = PDDocument.load(file);
    int numberOfPages = getPageCount(doc);
    System.out.println("The total number of pages "+numberOfPages);
    String content = new PDFTextStripper().getText(doc);
    doc.close();    
    return content;
}

3. 调用逻辑(无需修改)

try {
    JSclick(download);
    String filePath = isFileDownloaded("Personal Data", ".pdf", 30);
    if(filePath != null){
        String pdfContent = readPdfContent(filePath);
        Assert.assertTrue(pdfContent.contains("Test Kumar"));
        Assert.assertTrue(pdfContent.contains("XXXXX"));
    }else {
        System.out.println("Some issue with file downloading");
    }
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
优化建议(可选)

如果需要代码兼容Windows、Linux等多操作系统,可以将路径中的硬编码\\替换为File.separator,避免跨系统路径识别错误:

String folderName = System.getProperty("user.dir") + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "Download" + File.separator;

内容的提问来源于stack exchange,提问作者ankush singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 08:48:02