java – Read txt file whenever there are changes


I have a problem in a project I'm doing, I need to make a program that reads a txt file and imports it into MySQL, I managed to do even this part. But now I need this program to read this txt file whenever there are changes. And that it imports only the new registered data to MySQL. Could someone help me? Giving you some study tips. Or some example. I'm starting now in java. Thanks.

package teste;

import java.sql.*;   
import java.util.StringTokenizer;

class Teste{   
   public static void main(String args[]) {   
      try {   
         Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Radius","root","admin");   
         Statement stm = con.createStatement();   
         BufferedReader reader = new BufferedReader(new FileReader("c:\\Users\\solutel\\Documents\\tabela\\tabela.txt"));

         String dados[] = new String[3];         
         String linha = reader.readLine();   
         while (linha != null) {   
            StringTokenizer st = new StringTokenizer(linha,";\"");   
            dados[0] = st.nextToken();   
            dados[1] = st.nextToken();   

            stm.executeUpdate("insert into radcheck (username,attribute,op,value) values ('"+dados[0]+"','" +"User-Password"+ "','"+ ":="+ "','"+dados[1]+"')");   
            linha = reader.readLine();         
      catch (Exception e) {   
         System.err.println("Erro: " + e.getMessage());   


I did a quick search and found this library that might be useful for what you need: Jnotify


I was interested because it was something I could use in the future either pure java or java/android…

So I did some tests and I'll put here all the steps I made using Jnotify to monitor a folder or file, Created , Modified , Deleted or Renamed


Extract from the .zip file the .jar file and the file named jnotify.dll for 32-bit systems and jnotify_64bit.dll for 64-bit systems

NO ECLIPSE – After creating the project add the jar library to the example project here , then add the dll following these steps:

  1. Create a folder in the project named dll
  2. Put the .dll file in there
  3. In the project -> properties -> Java Build Path -> tab: Source click on yourproject/src and expand
  4. Click on Native library location and then on the EDIT button on the side
  5. Click on the Workspace button and select the dll folder created in the first step.

NO NETBEANS – Add the .jar to the project as explained in this link , and for the dll part I found the following steps:

  1. Access project properties
  2. Click on RUN
  3. In VM Options, fix: -Djava.library.path="C:\Directory where the DLL is"


This part is no mystery, I created a class with only the main method and what I needed as shown in the examples on the JNotify website.

import net.contentobjects.jnotify.JNotify;
import net.contentobjects.jnotify.JNotifyListener;

public class Main {

      public static void main(String[] args) {

            try {
            } catch (Exception e) {

      public static void observarPasta() throws Exception {

          // criei uma pasta temp para observar os arquivos que forem
          // criados e alterados dentro dela, mas pode ser alterado
          // para um arquivo especifico

          String path = "C:\\temp";

          // a mask é as ações que vão ser observadas, mas pode
          // ser utilizado JNotify.FILE_ANY para monitorar tudo
          // também.

          int mask = JNotify.FILE_CREATED  |
                     JNotify.FILE_DELETED  |
                     JNotify.FILE_MODIFIED |

          // monitorar subPastas?
          boolean watchSubtree = true;

          // adiciona o "MONITORADOR"
          int watchID = JNotify.addWatch(path, mask, watchSubtree, new Listener());

          //Fica esperando um tempo até terminar a aplicação
          //Dependendo da implementação da sua aplicação
          //isso não será necessário mas para esse teste é interessante

          // aqui remove o seu "MONITORADOR"
          boolean res = JNotify.removeWatch(watchID);

          if (!res) {
            // o id foi inválido.

          //essa implementação ja se explica com seus métodos
        static class Listener implements JNotifyListener {
          public void fileRenamed(int wd, String rootPath, String oldName, String newName) {
            print("renomeado " + rootPath + " : " + oldName + " -> " + newName);

          public void fileModified(int wd, String rootPath, String name) {
            print("modificado " + rootPath + " : " + name);

          public void fileDeleted(int wd, String rootPath, String name) {

            print("deletado " + rootPath + " : " + name);

          public void fileCreated(int wd, String rootPath, String name) {

            print("criado " + rootPath + " : " + name);

          void print(String msg) {
Scroll to Top