-1

I am trying to create a simple Java Program which implements KeyListener .

I want to run my program continuously until i abort it or upon a certain condition. What i wanted to do is after i run the program , whatever keys i pressed , it will get stored in the out.txt file.

public class StoreInFile implements KeyListener{
    public static void main(String[] args) {
    while(true){
    // **What should i do here such that it will call the keypressed event**.
    }
    }
    @Override
    public void keyPressed(KeyEvent e) {
        try{
              FileWriter fstream = new FileWriter("d:\\out.txt",true);
              BufferedWriter out = new BufferedWriter(fstream);
              out.write(e.getKeyChar());
              out.close();
              }catch (Exception ex){
              System.err.println("Error: " + ex.getMessage());
              }
    }

}

Is it possible to achieve in console Application? Basically i want to create a KeyLogger or KeyCatcher. How i can achieve this? Thanks in advance.

vikiiii
  • 9,246
  • 9
  • 49
  • 68

3 Answers3

2

For line based input, i.e. "users types text, user presses enter, your program receives what the user typed", the Scanner class should do just fine.

For single character input, such as "user presses x-key, your program receives a notification." you'll have to look into libraries such as CHARVA or Java Curses.

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • If i use a scanner class to read inputs , will it store the keys pressed only while my console window is active.What if open browser and type URL , will it store the URL keys also in the file? – vikiiii Jun 07 '12 at 09:20
  • No. Sounds like you're after a *key logger* or *key catcher*. Here's one project targeting Linux: http://sourceforge.net/projects/jxgrabkey and here's one project targeting windows: http://melloware.com/products/jintellitype/index.html – aioobe Jun 07 '12 at 13:35
  • +1 Hey.thanks for understanding my question.i want it on windows.Can you guide me a little ? Is JINTELLITYPE is a API for JAVA? – vikiiii Jun 07 '12 at 14:57
  • @vikiiii, yes, as most other libraries named JSomething :-) – aioobe Jun 07 '12 at 15:00
1

You can try a open source framework,jLine: jLine

But this is not 100% java.Some native implementation is also there.

UVM
  • 9,776
  • 6
  • 41
  • 66
0

If you're running on Windows, I will recommend JNA, and write keyhook and/or mousehook to monitor key/mouse events. It still works when your console window is inactive.

JNA Keyboard Hook in Windows

Working example of JNA mouse hook

Community
  • 1
  • 1
LiuYan 刘研
  • 1,614
  • 1
  • 16
  • 29