Read txt file whenever there are changes

Asked

Viewed 561 times

3

I have a problem in a project I’m doing, I need to do a program that reads a txt file and imports it to Mysql, I was able to do this part. But now I need this program to read this txt file whenever there are changes. And that matters to Mysql only the new data registered. Can anyone help me? Giving some study tips. Or some example. I’m starting now in java. Thank you.

package teste;

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

class Teste{   
   public static void main(String args[]) {   
      try {   
         Class.forName("org.gjt.mm.mysql.Driver");   
         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 could show you what you’ve done to get help.

  • 1

    I published in the topic below the program.

  • What do you mean? You should put it in your question, not as an answer. You created an answer and not a topic.

  • Sorry, it’s just that I’m new to the forum. I tried to copy here but it was too long.

  • 2

    All right, you get used to it. Here is not a Forum, it is a question and answer site.

  • Okay. You were able to help me?

  • you can create a function that reads the file from time to time, if the file has a size other than the previous one, then run the import.

  • Search for the Observer class and its use, in your case, it can help to do this monitoring automatically.

Show 3 more comments

1 answer

1

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

EDIT:

I was interested in being something that I could use in the future both pure java and java/android...

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

Configuring

Extract from the file .zip the file .jar and the file with the name jnotify.dll for systems 32 bits and jnotify_64bit.dll for systems 64 bits

IN THE ECLIPSE - After creating the project add the library jar to the project example here, then add to dll following these steps:

  1. Create a folder in the project with name dll
  2. Put the file . dll inside
  3. In the project -> properties -> Java Build Path -> tab: Source click on your/src project and expand
  4. Click on Native library Location and then on the EDIT button next to it
  5. Click the Workspace button and select the folder dll created in the first step.

IN NETBEANS - Add the .jar to the project as explained at that link, and for the part of dll i found the following steps:

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

Code

This part has no mystery, I created a class only with the method main and what it needed as it already shows in the examples of the site itself Jnotify.

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

public class Main {

      public static void main(String[] args) {

            try {
                  observarPasta();
            } catch (Exception e) {
                  e.printStackTrace();
            }
      }

      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 |
                     JNotify.FILE_RENAMED;

          // 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
          Thread.sleep(1000000);

          // 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) {
            System.err.println(msg);
          }
        }
}
  • Good afternoon Furflez, I was able to leave in real time according to your code, but when I change the txt file adding more data. The program inserts the repeated data into Mysql and the more the added. It can help me to insert only the added data. Thank you very much.

  • Well, I looked at what might have been, and found in a stackoverflowEN response the same problem, and this might be due to the operating system... I have two suggestions but depend on the way you work within those files. you could instead of taking the modification event, delete the file as soon as it reads and wait for the creation of a new one in the method fileCreated... or keep in a variable the last data for comparison if that has already been "worked" as for example a line index, number of characters... I believe this can help you...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.