I have the following code in which I want 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();
}
}
}