6.7.16

Java Code Snippets

Some random code snippets...

Running JavaScript via WebDriver -


JavascriptExecutor jsRunner = (JavascriptExecutor) driver;

// This will get us the name of the browser on which the test is running
String jsString = "return navigator.appCodeName";
System.out.println ("BrowserName = " + jsRunner.executeScript(jsString));

Code to get the text of all the links on a web page -

List<WebElement> allLinks = driver.findElements(By.tagName("a"));
for (WebElement link : allLinks){
     System.out.println("Link text = " + link.getText());
}

File copy - just ensure that the folder path has a \\ in the end, otherwise, the files wont be copied/deleted and even strange-ly, there wont be any errors!

    //Function to copy all the files in a dir, but will not replace if the file already exists
    public void copyAllFilesToDir(String sourceDir, String destinationDir){
        String fileName = null;

        File folder = new File(sourceDir);
        File[] listOfFiles = folder.listFiles();
        //loop through all the files in the dir
        for (int i =0; i < listOfFiles.length; i++){
            //check if the item is a file or a folder
            if(listOfFiles[i].isFile()){
                fileName = listOfFiles[i].getName();
                copyFile(sourceDir + fileName, destinationDir + fileName);
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.getMessage();
                }
            }
        }
    }

    //Function to delete all files in a dir
    public void deleteAllFiles(String dirPath){

        File folder = new File(dirPath);
        File[] listOfFiles = folder.listFiles();
        for (int i = 0; i < listOfFiles.length; i ++){
            if (listOfFiles[i].isFile()){
                if(listOfFiles[i].delete()){
                    System.out.println("file deleted -" + listOfFiles[i].getName());
                }else {
                    System.out.println("could NOT delete file -" + listOfFiles[i].getName());
                }
            }
        }
    }

    //Function to copy one file at a time, does not overwrite/replace existing files
    public void copyFile(String sourceFilePath,String destinationFilePath){
        File sourceFile = new File(sourceFilePath);
        File destinationFile = new File(destinationFilePath);
        try {
            FileUtils.copyFile(sourceFile, destinationFile);
        } catch (IOException e) {
            e.getMessage();
        }
    }

No comments:

Post a Comment