A while back, I encountered a useful short perl script which runs in the background of a terminal, and periodically checks a file for changes, and when it detects one, it runs a specified command. That was very useful for writing LaTeX documents: when I saved the file, I could use the script to auto-run latex on it. I found the idea fascinating, and wanted to bring it over into the windows world. Here’s a java code that does the same thing; it has a Swing interface that is pretty self-explanatory. An entertaining trick to try– and one of the ways I tested it– is to use a command that changes the file everytime it is changed.
[java]
import java.lang.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//Runs a command when a file is modified
public class doOnModGui extends JPanel implements ActionListener, Runnable {
JTextField cmdField, fileField;
Thread task = new Thread(this);
boolean dataValid = false;
File monitor;
String cmd;
long lastMod;
GridBagConstraints constraints = new GridBagConstraints();
public doOnModGui() {
JButton taskButton = new JButton(”Set Task”);
taskButton.addActionListener(this);
setLayout(new GridBagLayout());
addGB(new JLabel(”File to monitor: “), 0,0);
addGB(fileField = new JTextField(20), 1,0);
addGB(new JLabel(”Task to run: “), 0, 1);
addGB(cmdField = new JTextField(20), 1,1);
constraints.gridwidth=2;
addGB(taskButton, 0,2);
task.setDaemon(true);
task.start();
}
void addGB( Component component, int x, int y) {
constraints.gridx = x;
constraints.gridy = y;
add(component, constraints);
}
synchronized public void actionPerformed(ActionEvent e) {
dataValid = true;
monitor = new File(fileField.getText());
cmd = cmdField.getText();
lastMod = monitor.lastModified();
notify();
}
synchronized public void run() {
try{
while(true) {
if(!dataValid)
wait();
if(Math.abs(lastMod - monitor.lastModified())>0) {
Runtime rt = Runtime.getRuntime();
lastMod = monitor.lastModified();
try {
Process proc = rt.exec(”cmd /c ” ” + cmd + ” && exit ” “);
proc.waitFor();
}
catch(IOException e) {
System.out.println(”Error encountered running command: “);
System.out.println(e.getMessage());
};
}
wait(25);
}
}
catch (InterruptedException e) {}
}
public static void main(String[] args) {
JFrame frame = new JFrame(”Run task on file modification”);
frame.getContentPane().add(new doOnModGui(), “Center”);
frame.addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.out.println(”Exiting..”);
System.exit(0);
}
});
frame.pack();
frame.setVisible(true);
}
}
[/java]
Possibly relevant posts: