I need to create a program that copies numbers from a window to a java file. 1 Since the numbers are not in a web browser, I can't scan a regular website for the data. I can, however, click on the number and press Ctrl + C to copy them. I basically need something that reads some given coordinates on my screen or something that can click on the numbers and copy and paste them into a text file.
Asked
Active
Viewed 62 times
2 Answers
0
Since (presumably) you can use Ctrl+C
to copy the text, you can use the system clipboard. You could use the instructions in this Stack Overflow Answer to read the system clipboard.
By relying on the system clipboard, you can work around the problem of reading a certain portion of the screen and do some character recognition.

Community
- 1
- 1

Kedar Mhaswade
- 4,535
- 2
- 25
- 34
-
-
Hey downvoter! Can you please explain why you did that? My answer was given credit by the accepted answer and I get a downvote? WHY? – Kedar Mhaswade Mar 19 '17 at 18:47
0
The java.awt.Robot
class can be used to do the clicking and key pressing. The java.awt.datatransfer.Clipboard
class can be used to read the clipboard. Needed imports:
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.KeyEvent;
import java.awt.event.InputEvent;
import java.io.IOException;
Example code (note that AWTException
, UnsupportedFlavorException
, and IOException
must be handled, perhaps by throws Throwable
in the method header):
// Things that need to be set up only once.
final Robot robot = new Robot();
final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
// If you need a loop, start it here.
for (;;) {
// Click at (x, y).
robot.mouseMove(x, y);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(100);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(100);
// Press Ctrl+C.
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_C);
robot.delay(100);
robot.keyRelease(KeyEvent.VK_C);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.delay(100);
// Read clipboard.
final String clipboardContents = (String) clipboard.getData(DataFlavor.stringFlavor);
// Work with clipboard contents.
System.out.println(clipboardContents);
}
As far as putting the copied data into a text file, how you want to do that is up to you:
- You can modify the above to strip out the parts dealing with the clipboard contents and simply use the
Robot
to click on a different window and press Ctrl+V. - You can modify the above to open a text file, write the clipboard contents to it, and save it.
Credit to:
- Kedar Mhaswade's answer to this question points to an answer to "Get readable text only from clipboard"
- Answer to "how to send CTRL+Z keyEvent in java using Robot class"

Chai T. Rex
- 2,972
- 1
- 15
- 33