package newpackage;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class KeyBoardListener extends JFrame {
JPanel jPanel;
JLabel UserName,PassWord;
char charA;
public KeyBoardListener()
{
this.setSize(300,200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Keylogger");
this.setVisible(true);
this.addKeyListener(new MyKeyListener());
jPanel = new JPanel();
UserName = new JLabel("UserName");
jPanel.add(UserName);
PassWord = new JLabel("PassWord");
jPanel.add(PassWord);
add(jPanel);
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
KeyBoardListener m = new KeyBoardListener();
}
}
class MyKeyListener extends KeyAdapter
{
public void keyPressed(KeyEvent e)
{
char charA = e.getKeyChar();
String s = null;
try {
s = "You pressed "+charA+" at "+getTime()+"\n";
}
catch (ParseException ex)
{
Logger.getLogger(MyKeyListener.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(s);
File file = new File("D:\\temp\\test");
FileOutputStream f = null;
try
{
f = new FileOutputStream(new File("D:\\temp\\test.txt"));
}
catch (FileNotFoundException ex)
{
Logger.getLogger(MyKeyListener.class.getName()).log(Level.SEVERE, null, ex);
}
PrintStream p = new PrintStream(f);
p.println(s);
p.close();
}
private Date getTime() throws ParseException
{
Date d = new Date();
String s = null;
s = DateFormat.getDateInstance().format(d);
s = DateFormat.getDateInstance(DateFormat.DEFAULT).format(d);
s = DateFormat.getDateInstance(DateFormat.FULL).format(d);
s = DateFormat.getDateInstance(DateFormat.MEDIUM).format(d);
s = DateFormat.getDateInstance(DateFormat.SHORT).format(d);
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
s = sdf.format(d);
DateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
s = sdf2.format(d);
DateFormat sdf3 = new SimpleDateFormat("yyyyMMddHHmmss");
s = sdf3.format(d);
s = sdf.format(d);
Date today = sdf.parse(s);
Calendar c = Calendar.getInstance();
return c.getTime();
}
}
這是一個記錄鍵盤的小程序
我想把運行結果輸出到一個TXT 文件內,但是運行後測試,TXT 文件內只會記錄最新的一條記錄,應該怎樣更改才能顯示所有的記錄,求解答
而且在JFrame中JLabel的內容時而顯示時而不顯示,這是什麼原因
修正下這行創建f的代碼為如下,第二個參數表示追加到原來文件後面:
try
{
f = new FileOutputStream(new File("D:\\temp\\test.txt"),true);
}