Crazy Eddy Crazy Eddy - 5 months ago 18
Java Question

How can I continously check to see if the text inside a text file has changed to empty? Java

I need the following code to read what is in the text file and display in textField2 weather it has changed or not... If it has, then I need it to continue. If it hasn't, then I need it to check again until the file has been changed to empty. Can anyone help? Here is my code:





package application;

import javafx.event.ActionEvent;
import javafx.scene.control.TextField;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Parent;
import javafx.fxml.FXMLLoader;
import javafx.fxml.FXML;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;


public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
// BorderPane root = new BorderPane();
Parent root = FXMLLoader.load(getClass().
getResource("Root.fxml"));

Scene scene = new Scene(root,550,400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
launch(args);
}

@FXML
private TextField textField;

@FXML
private TextField textField2;

@FXML
protected void onClick(ActionEvent event) throws IOException {
BufferedWriter writer = null;
try {
//create a temporary file


// This will output the full path where the file will be written to...


writer = new BufferedWriter(new FileWriter("C:/Users/Custom/Documents/Sample.txt"));
writer.write(textField.getText());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close the writer regardless of what happens...
writer.close();
} catch (Exception e) {
}
while (readFile("C:/Users/Custom/Documents/Sample.txt") != ""){
textField2.setText("Waiting...");
}
textField2.setText("Done!");


}
}

String readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();

while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
}




Answer

Hi you can make a timer to check the file once every 2 seconds or so a snippet goes here

new java.util.Timer().schedule( 
    new java.util.TimerTask() {
        @Override
        public void run() {
            //Read your file
            if(fileEmpty){
               //Update your textfiled
               cancel(); //Stops this timer 
            }
        }
    }, 
    0,2000);

once your task is done just use purge(); to clear out all cancelled timers

hope this helps