How to display GUI content to a txt file?

118 Views Asked by At

I am new to Java and specifically JavaFx, I have created a project to track my food intake through a GUI but I wish to save that data to a .txt file so I can store the data. Currently, the GUI works well, but I am having trouble storing the data in the .txt file. I have imported the file into the project folder, and here is my code.

MainClass:

package Pck1;

public class MainClass extends Application {
    
    final int stageWidth = 1000;
    final int stageHeight = 720;
    final int paneWidth = stageWidth - 100;
    final int paneHeight = stageHeight - 120;
    
    public static ArrayList<Food> list;

    public static void main(String[] args) {
        
        list = new ArrayList<Food>(10);
        launch();

    }   
    
                public void start(Stage stage) {
        
        Font font11 = Font.font("verdana", FontWeight.NORMAL,
                FontPosture.REGULAR, 11);
        Font font12 = Font.font("verdana", FontWeight.NORMAL, 
                FontPosture.REGULAR, 12);
        
        Font font14 = Font.font("verdana", FontWeight.BOLD,
                FontPosture.REGULAR, 14);
        Font font18 = Font.font("verdana", FontWeight.BOLD,
                FontPosture.REGULAR, 18);
        
        Label lbRecord = new Label("Records:");
        lbRecord.setLayoutX(25);
        lbRecord.setLayoutY(20);
        lbRecord.setFont(font18);
        
        Label lbDate = new Label("Date:");
        lbDate.setLayoutX(550);
        lbDate.setLayoutY(55);
        lbDate.setFont(font18);
        
        Label lbTime = new Label("Time:");
        lbTime.setLayoutX(550);
        lbTime.setLayoutY(100);
        lbTime.setFont(font18);
        
        Label lbTypeOfFood = new Label("Type of Food:");
        lbTypeOfFood.setLayoutX(550);
        lbTypeOfFood.setLayoutY(145);
        lbTypeOfFood.setFont(font18);
        
        Label lbAmtOfFood = new Label("Amount of Food:");
        lbAmtOfFood.setLayoutX(550);
        lbAmtOfFood.setLayoutY(190);
        lbAmtOfFood.setFont(font18);
        
        TextField tfDate = new TextField();
        tfDate.setLayoutX(800);
        tfDate.setLayoutY(55);
        
        TextField tfTime = new TextField();
        tfTime.setLayoutX(800);
        tfTime.setLayoutY(100);
        
        TextField tfTypeOfFood = new TextField();
        tfTypeOfFood.setLayoutX(800);
        tfTypeOfFood.setLayoutY(145);
        
        TextField tfAmtOfFood = new TextField();
        tfAmtOfFood.setLayoutX(800);
        tfAmtOfFood.setLayoutY(190);
        
        TextArea tA = new TextArea();
        tA.setPrefRowCount(20);
        tA.setLayoutX(25);
        tA.setLayoutY(50);
        tA.setMinSize(500, 400);
        tA.setFont(font12);
        
        Button btnClear = new Button("Clear");
        btnClear.setFont(font18);
        btnClear.setFocusTraversable(false);
        btnClear.setLayoutX(25);
        btnClear.setLayoutY(475);
        
        Button btnShow = new Button("Show List");
        btnShow.setFont(font18);
        btnShow.setFocusTraversable(false);
        btnShow.setLayoutX(125);
        btnShow.setLayoutY(475);
        
        Button btnSubmit = new Button("Submit");
        btnSubmit.setFont(font18);
        btnSubmit.setFocusTraversable(false);
        btnSubmit.setLayoutX(550);
        btnSubmit.setLayoutY(220);
        
        Pane p = new Pane();
        p.setMinSize(paneWidth, paneHeight);
        p.setBackground(new Background(new BackgroundFill(Color.rgb(173, 216, 230),
                null, null)));
        p.getChildren().addAll(lbRecord, tA);
        p.getChildren().addAll(lbDate, tfDate);
        p.getChildren().addAll(lbTime, tfTime);
        p.getChildren().addAll(lbTypeOfFood, tfTypeOfFood);
        p.getChildren().addAll(lbAmtOfFood, tfAmtOfFood);
        p.getChildren().addAll(btnClear, btnShow, btnSubmit);
        
        btnClear.setOnAction((ActionEvent e) -> {
        try {
                tA.clear();
        } catch (Exception ex) {
            tA.setText(ex.toString());
        }
        });
        btnShow.setOnAction((ActionEvent e) -> {
            try {
                tA.clear();
                String buffer = "";
                for (int i = 0; i < list.size(); i++) {
                    buffer += list.get(i).date + "\n";
                    buffer += list.get(i).time + " " + list.get(i).typeOfFood + " " + list.get(i).amtOfFood 
                            +"\n\n";
                }
                
                tA.setText(buffer);
            } catch(Exception ex) {
                tA.setText(ex.toString());
            }
            });
        
        btnSubmit.setOnAction((ActionEvent e) -> {
            try {
                String buf = tA.getText() + "\n";
                buf += tfDate.getText() + "\n";
                buf += tfTime.getText() + "\n";
                buf += tfTypeOfFood.getText() + "\n";
                buf += tfAmtOfFood.getText() + "\n";
                tA.setText(buf);
                
                list.add(new Food(tfDate.getText(),
                        tfTime.getText(),
                        tfTypeOfFood.getText(), tfAmtOfFood.getText()));
            } catch(Exception ex) {
                tA.setText(ex.toString());
            }
        });
        
        VBox vb = new VBox();
        vb.setPadding(new Insets(15, 15, 15, 15));
        vb.setSpacing(15);
        vb.setBackground(new Background(new BackgroundFill(Color.rgb(0, 0, 0), null, null)));
        vb.getChildren().addAll(p);
        
        Scene scene = new Scene(vb);
        stage.setScene(scene);
        stage.setTitle("Food Diary");
        stage.setWidth(1100.0);
        stage.setHeight(700.0);
        stage.show(); 

            
        String filename = "FoodDiary.txt";
            
        btnSubmit.setOnAction((ActionEvent e) -> {
            try {
                
                String buf = tA.getText() + "\n";
                buf += tfDate.getText() + "\n";
                buf += tfTime.getText() + "\n";
                buf += tfTypeOfFood.getText() + "\n";
                buf += tfAmtOfFood.getText() + "\n";
                tA.setText(buf);
                
                FileProcessing fP = new FileProcessing(filename);
                fP.inputBuffer = tfDate.getText() + "\n";
                fP.inputBuffer = tfTime.getText() + "\n";
                fP.inputBuffer = tfTypeOfFood.getText() + "\n";
                fP.inputBuffer = tfAmtOfFood.getText() + "\n";
                fP.WriteDataToFile();
                
                fP.inputBuffer = tfDate.getText() + "\n";
                fP.inputBuffer = tfTime.getText() + "\n";
                fP.inputBuffer = tfTypeOfFood.getText() + "\n";
                fP.inputBuffer = tfAmtOfFood.getText() + "\n";
                fP.AppentDataToFile();
                
                fP.inputBuffer = tfDate.getText() + "\n";
                fP.inputBuffer = tfTime.getText() + "\n";
                fP.inputBuffer = tfTypeOfFood.getText() + "\n";
                fP.inputBuffer = tfAmtOfFood.getText() + "\n"; 
                fP.AppentDataToFile();
                
                list.add(new Food(tfDate.getText(),
                    tfTime.getText(),
                    tfTypeOfFood.getText(), tfAmtOfFood.getText()));
                
                fP = new FileProcessing(filename);
                fP.ReadDataAndStoreToBuffer();
            } catch(Exception ex) {
                    tA.setText(ex.toString());
            }
        });
}
}

And here is my FileProcessing class:

package Pck1;

public class FileProcessing {

    String filename = "FoodDiary.txt";
    String inputBuffer; 
    String outputBuffer;
    
    File fptr;
    Scanner fin;
    
    public FileProcessing(String filename) {
        filename = this.filename;
        inputBuffer = "";
        fptr = null;
        
        OpenFile();
    }
    
    public void OpenFile() {
        try {
            fptr = new File(filename);
            if(!fptr.exists()) {
                System.out.println("OpenFile: Creating new file");
                fptr.createNewFile();
            }
            fin = new Scanner(fptr);
        }
        catch (IOException ex) {
            System.out.println("OpenFile:File exception occured");
            ex.printStackTrace();
            System.exit(0);
        }
        return;
    }
    
    public void ReadDataAndStoreToBuffer() {
        
        outputBuffer = "";
        while (fin.hasNext()) {
            outputBuffer += fin.nextLine() + "\r\n";
        }
        fin.close();
        return;
    }
    
    public String ReadNextLine() {
        
        outputBuffer = "";
        if(fin.hasNext()) {
            outputBuffer = fin.nextLine() + "\r\n";
        } else {
            fin.close();
        }
        return outputBuffer;
    }
    
    public void WriteDataToFile() {
        
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(fptr);
            pw.println(inputBuffer);
        } catch (IOException ex) {
            System.out.println("WriteDataToFile: File exception occured");
            ex.printStackTrace();
        } finally {
            pw.close();
        }
         return;
    }
    
    public void AppentDataToFile() {
        
        FileWriter fw = null;
        PrintWriter ppw = null;
        
        try {
            fw = new FileWriter(fptr, true);
            ppw = new PrintWriter(fw);
            ppw.print(inputBuffer + "\r\n");
        } catch (IOException ex) {
            System.out.println("AppendDataToFile:File exception occuered");
            ex.printStackTrace();
        } finally {
            ppw.close();
        }
      return; 
}
}

I asked my professor for help with this problem, and he gave me the skeleton for the file-processing part of the code, which I altered to fit the parameters of my project.

2

There are 2 best solutions below

4
David Weber On BEST ANSWER

Storing Data:

Step 1: Add this dependency:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>

Step 2: Convert your list to JSON

String jsonString = new Gson().toJson(list);

Step 3: Write this JSON String to a File.

Path path = new File(fileName).toPath();
Files.write(path, jsonString.getBytes());

https://www.baeldung.com/java-write-to-file

Loading data:

Step 1: Get the File

File loadedFile = new File(...);

Step 2: Get the files content

String fileContent = Files.readString(loadedFile);

Step 3: Convert file content to List

List<X> = new Gson().fromJson(fileContent, List<X>.class);
4
Basil Bourque On

As others noted, apparently you are asking simply how to write a file. This has nothing to do with JavaFX.

Here is some example code. We define a Food record as a record. We make some dummy data. We write that data to storage using the convenient Paths & Files utility class methods provided by the modern Java NIO file framework. We export our Food records as simple TAB-delimited file. Then we read that data, instantiating Food record objects.

public class FoodRepository
{
    private final String FIELD_SEPARATOR = Character.toString ( 9 );  // TAB
    private final Path path = Paths.get ( "/Users/your_user_here/" , "FoodDiary.txt" );

    boolean save ( final SequencedCollection < Food > foods )
    {
        SequencedCollection < String > lines = new ArrayList <> ( foods.size ( ) );
        for ( Food food : foods )
        {
            String line = food.name ( ).concat ( FIELD_SEPARATOR ).concat ( String.valueOf ( food.quantity ( ) ) );
            lines.add ( line );
        }
        try
        {
            Files.write ( path , lines );
            return true;
        }
        catch ( IOException e ) { throw new RuntimeException ( e ); }
    }

    SequencedCollection < Food > fetch ( )
    {
        try
        {
            List < String > lines = Files.readAllLines ( path , StandardCharsets.UTF_8 );
            System.out.println ( "lines = " + lines );
            List < Food > foods = new ArrayList <> ( lines.size ( ) );
            for ( String line : lines )
            {
                System.out.println ( "line = " + line );
                String[] parts = line.split ( FIELD_SEPARATOR );
                Food food = new Food ( parts[ 0 ] , Integer.parseInt ( parts[ 1 ] ) );
                foods.add ( food );
            }
            return foods;
        }
        catch ( IOException e ) { throw new RuntimeException ( e ); }
    }

    public static void main ( String[] args )
    {
        SequencedCollection < Food > foods =
                List.of (
                        new Food ( "Apple" , 1 ) ,
                        new Food ( "Banana" , 2 ) ,
                        new Food ( "Carrot" , 3 )
                );
        FoodRepository repository = new FoodRepository ( );
        if ( repository.save ( foods ) )
        {
            SequencedCollection < Food > foodsAgain = repository.fetch ( );
            System.out.println ( "foodsAgain = " + foodsAgain );
        } else throw new RuntimeException ( "Failed to save food diary to text file." );
    }
}

record Food( String name , int quantity ) { }

When run:

lines = [Apple  1, Banana   2, Carrot   3]
line = Apple    1
line = Banana   2
line = Carrot   3
foodsAgain = [Food[name=Apple, quantity=1], Food[name=Banana, quantity=2], Food[name=Carrot, quantity=3]]