Robot API (java.awt.Robot) is a Java built-in class that can simulate keyboard and mouse events at the operating system level — outside the browser. It is commonly used in Selenium for handling native OS dialogs like file upload windows.
Import and create Robot:
Java
import java.awt.Robot;
import java.awt.event.KeyEvent;
Robot robot = new Robot();
Simulate keyboard events:
Java
// Press Enter key
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
// Type a file path (for upload dialog)
robot.keyPress(KeyEvent.VK_C); // Press C
robot.keyRelease(KeyEvent.VK_C);
Copy file path to clipboard and paste in dialog:
Java
// Copy path to clipboard using Java Toolkit
StringSelection selection = new StringSelection("C:\\files\\upload.pdf");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, null);
// Paste using Robot
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
Limitations:
- ✓Works only on the local machine (not Selenium Grid or remote machines)
- ✓OS and resolution dependent
- ✓Prefer
sendKeys("file path")directly on<input type="file">when possible
