Selenium:用Java打开下载的文件

时间:2017-07-07 01:03:04

标签: java file selenium download

我需要使用selenium打开并阅读下载的文件,我不太清楚如何操作。我看到建议在选定位置下载文件的答案。我的代码是否真的需要从将文件下载到选定位置开始,还是可以在下载后直接启动?

打开文件后我也必须阅读它。任何人都可以告诉我如何做到这一点?谢谢!

2 个答案:

答案 0 :(得分:0)

您可以使用以下代码阅读文件:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileExample1 {

    private static final String FILENAME = "E:\\test\\filename.txt";

    public static void main(String[] args) {

        BufferedReader br = null;
        FileReader fr = null;

        try {

            fr = new FileReader(FILENAME);
            br = new BufferedReader(fr);

            String sCurrentLine;

            br = new BufferedReader(new FileReader(FILENAME));

            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            try {

                if (br != null)
                    br.close();

                if (fr != null)
                    fr.close();

            } catch (IOException ex) {

                ex.printStackTrace();

            }

        }

    }

}

希望它会对你有所帮助。

答案 1 :(得分:0)

您可以使用这行代码从chrome和forefox浏览器下载文件。

public static File waitForDownloadToComplete(File downloadPath, String fileName) throws Exception {
        boolean isFileFound = false;
        int waitCounter = 0;
        while (!isFileFound) {
            logger.info("Waiting For Download To Complete....");
            for (File tempFile : downloadPath.listFiles()) {
                if (tempFile.getName().contains(fileName)) {
                    String tempEx = FilenameUtils.getExtension(tempFile.getName());
                    // crdownload - For Chrome, part - For Firefox
                    if (tempEx.equalsIgnoreCase("crdownload") || tempEx.equalsIgnoreCase("part")) {
                        Thread.sleep(1000);
                    } else {
                        isFileFound = true;
                        logger.info("Download To Completed....");
                        return tempFile;
                    }
                }
            }
            Thread.sleep(1000);
            waitCounter++;
            if (waitCounter > 25) {
                isFileFound = true;
            }
        }
        throw new Exception("File Not Downloaded");
    }
}