javauser-interfacejavafxfile-processing

How to display GUI content to a txt file?


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 the relevant code.

MainClass:

        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());
            }
        });
}
}

I also have a "FileProcessing" Class that my professor gave me, and I altered to fit my project. There are no issues in this part of the code.


Solution

  • 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 class 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 & NIO.2 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]]
    

    For earlier versions of Java, you can replace record with a conventional class definition. In place of SequencedCollection, use List.