JamesB
JamesB

Reputation: 529

Problems in thread writing local txt file

I am trying to use this class isolated to write from text from a lot of sources without opening one instance or connection of the file per time, so I add to an ArrayList and it works in an isolated thread to see if the row, so the service class do the job of writing the information as soon as possible avoiding client classes to wait its time to use writer class. The problem of this class is that I am executing the thread in the constructor but the thread stops in the first call in to execute the method write (gerenciadorDeArquivos().escreveEmArquivo(), it writes one time in the file and no more, this when I put the program in debugging, if I don't he does not execute not even once. Maybe you can give some insights.

Main form class

package EscreveArquivo;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;


public class Tela extends javax.swing.JFrame {

public Tela() {
    initComponents();
}
 private void initComponents() {....} /// Form Components

 EscreveArquivo escritorDeArquivos = new EscreveArquivo();

   private void recordTextButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                 
    escritorDeArquivos.AdicionaArquivoEmListaDeInstrucoes(textField.getText());
}               

Second Class

package Escrevearquivo;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;*

public class EscreveArquivo {

private static List<String> listaDeInstrucoes = new ArrayList<String>();
private boolean gerenciadorEstaEmExecucao = false;

EscreveArquivo() {
    Thread t = new Thread() {   
        public void run() //Anonymous class overriding run() method of Thread class
        {
            while (true) {
                if (!listaDeInstrucoes.isEmpty()) {
                    gerenciadorDeArquivos();
                }
            }
        }
    };
    t.start();
}

public static void AdicionaArquivoEmListaDeInstrucoes(String arquivoASerEscrito) {
    listaDeInstrucoes.add(arquivoASerEscrito);
}

private void gerenciadorDeArquivos() {

    if (gerenciadorEstaEmExecucao == false) {
        gerenciadorEstaEmExecucao = true;

        ArrayList<String> listaDeInstrucoesCopia = new ArrayList<String>();
        for (String textoAEscrever : listaDeInstrucoes) {
            listaDeInstrucoesCopia.add(textoAEscrever);
        }
        for (String textoAApagar : listaDeInstrucoesCopia) {
            EscreveEmArquivo(textoAApagar);
            listaDeInstrucoesCopia.remove(textoAApagar);
        }
    }
    gerenciadorEstaEmExecucao = false;
}

private static void EscreveEmArquivo(String texto) {
    File arquivo = new File("C://Users//Josué//Desktop//arquivoTexto.txt");
    try {
        if (!arquivo.exists()) {
            arquivo.createNewFile();
        }
        FileWriter writer = new FileWriter(arquivo, true);
        BufferedWriter saida = new BufferedWriter(writer);
        saida.write(texto);
        saida.newLine();
        saida.close();

    } catch (IOException ex) {
        Logger.getLogger(Tela.class
                .getName()).log(Level.SEVERE, null, ex);
    }
}

}

Upvotes: 0

Views: 73

Answers (1)

Kris
Kris

Reputation: 8863

The section

for(String textoAApagar : listaDeInstrucoesCopia) {
   EscreveEmArquivo(textoAApagar);
   listaDeInstrucoesCopia.remove(textoAApagar); //error will be thrown here!
}

will actually generate an error for ConcurrentModificationException because, you are modifying the list listaDeInstrucoesCopia while you are traversing it. So in that case, the call will not go for writing the second field. Only the first call will get executed.

Remove the line listaDeInstrucoesCopia.remove(textoAApagar); , it should work fine. But again you are not emptying your ArrayList, so old values will be re-written.

You should consider using a Queue implementation and pop the end element and write to file continuously.

Upvotes: 1

Related Questions