Home > Software design >  Java - Create a text file on the first run
Java - Create a text file on the first run

Time:12-12

I'm trying to make an application that takes a username and password to store into a text document. However, I can't seem to get the application to create the file on the first run, it only seems to work if I manually create the file. I've tried changing up when I make the file in the DataCenter, but I keep getting the same error:

Caused by: java.io.FileNotFoundException: file.txt (The system cannot find the file specified)
    at java.base/java.io.FileInputStream.open0(Native Method)
    at java.base/java.io.FileInputStream.open(FileInputStream.java:216)
    at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)
    at java.base/java.util.Scanner.<init>(Scanner.java:641)
    at Q02.start(Q02.java:31)
public class DataCenter {
   private static String filename = "file.txt";
   private File file;
   private static DataCenter instance = null;

   private DataCenter() {
       if (instance != null) {
           throw new Error();
       }
       file = new File(filename);
   }

   public static DataCenter getInstance() {
      if (instance == null) {
          instance = new DataCenter();
      }
      return instance;
   }

   public File getFile() {
       return file;
   }
}

public class UserData {

    private String username;
    private String password;
    
    public UserData() {
        
    }
    
    public UserData(String username, String password) {
        this.username = username;
        this.password = password;
    }
    
    public void setUsername(String username) {
        this.username = username;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getUsername() {
        return this.username;
    }
    public String getPassword() {
        return this.password;
    }
    public String toString() {
        return "Username: "   this.username   " Password: "   this.password;
    }
    public boolean equals(UserData object) {
        boolean equals = true;
        if(!(this.username.equals(object.username)))
            equals = false;
        return equals;
    }
}
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Q02 extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        DataCenter center1 = DataCenter.getInstance();
        Alert a = new Alert(AlertType.NONE);
        int userIndex = 0;
        int passIndex = 1;
        ArrayList<UserData> users = new ArrayList<>();
        ArrayList<String> userData = new ArrayList<>();
        Scanner sc = new Scanner(center1.getFile());
        while(sc.hasNext()) {
            userData.add(sc.next());
        }
        for(int i = 0; i < userData.size()/2; i  ) {
            users.add(new UserData(userData.get(userIndex),userData.get(passIndex)));
            userIndex = userIndex 2;
            passIndex = passIndex 2;
        }
        VBox vbox = new VBox();
        VBox vbox1 = new VBox();
        HBox hbox = new HBox();
        GridPane root = new GridPane();
        TextField tfUser = new TextField();
        TextField tfPass = new TextField();
        TextField tfConfirm = new TextField();
        Label username = new Label("Username");
        Label password = new Label("Password");
        Label confirm = new Label("Confirm Password");
        vbox.getChildren().addAll(tfUser,tfPass,tfConfirm);
        vbox1.getChildren().addAll(username, password, confirm);
        Button btnSignUp = new Button("Sign Up");
        btnSignUp.setDisable(true);
        btnSignUp.setOnAction(e -> {
            boolean userExists = false;
            UserData user = new UserData(tfUser.getText(),tfPass.getText());
            for(int i = 0; i < users.size(); i  ) {
                if(user.getUsername().equals(users.get(i).getUsername())) {
                    a.setAlertType(AlertType.CONFIRMATION);
                    a.setContentText("Registration Failed!");
                    a.show();
                    userExists = true;
                }
            }
            //System.out.println(user);
            if(userExists == false) {
            try {
            PrintWriter pw = new PrintWriter(new FileWriter(center1.getFile(),true));
            pw.append(tfUser.getText()   " ");
            pw.append(tfPass.getText()  " ");
            users.add(user);
            a.setAlertType(AlertType.CONFIRMATION);
            a.setContentText("Registration Complete!");
            a.show();           
            pw.close();
            } catch(Exception ex) {
                ex.printStackTrace();
            }
            }           
        });
        tfPass.setOnKeyTyped(new EventHandler<KeyEvent>() {
            public void handle(KeyEvent e) {
                String username = tfUser.getText();
                String password = tfPass.getText();
                String confirm = tfConfirm.getText();
                btnSignUp.setDisable(!validateUserLogin(username,password,confirm));
            }
        });
        tfUser.setOnKeyTyped(new EventHandler<KeyEvent>() {
            public void handle(KeyEvent e) {
                String username = tfUser.getText();
                String password = tfPass.getText();
                String confirm = tfConfirm.getText();
                btnSignUp.setDisable(!validateUserLogin(username,password,confirm));
            }
        });
        tfConfirm.setOnKeyTyped(new EventHandler<KeyEvent>() {
            public void handle(KeyEvent e) {
                String username = tfUser.getText();
                String password = tfPass.getText();
                String confirm = tfConfirm.getText();
                btnSignUp.setDisable(!validateUserLogin(username,password,confirm));
            }
        });
        Button btnCancel = new Button("Cancel");
        btnCancel.setOnAction(e -> {
            tfUser.setText("");
            tfPass.setText("");
            tfConfirm.setText("");
        });
        hbox.getChildren().addAll(btnSignUp, btnCancel);
        hbox.setSpacing(8);
        root.add(vbox, 1, 0);
        root.add(vbox1, 0, 0);
        root.add(hbox, 1, 3);
        hbox.setPadding(new Insets(8));
        vbox.setSpacing(8);
        vbox1.setSpacing(16);
        root.setAlignment(Pos.CENTER);
        vbox.setAlignment(Pos.CENTER);
        vbox1.setAlignment(Pos.CENTER_RIGHT);
        vbox1.setPadding(new Insets(5));
        Scene login = new Scene(root,400,400);
        stage.setScene(login);
        stage.show();
    }
    
    public static void main(String args[]) {
        Application.launch();
    }
    
    private boolean validateUserLogin(String username, String password, String confirmation) {
        boolean login = true;
        if(!(username.length() >= 6 && password.length() >= 6)) {
            login = false;
        }
        if(!(password.equals(confirmation))) {
            login = false;
        }
        return login;
        
    }
}

CodePudding user response:

Check if the file exists in the first line of your main method and if don't exist create it :

    public static void main(String args[]) throws IOException {
        if (Files.notExists(Path.of("YOUE-FILE_PATH"))) {
            Files.createDirectories(Path.of("PARENT-FOLDER"));
            Files.createFile(Path.of("YOUE-FILE_PATH"))
        }

        Application.launch();
    }

And if you use older java 11 you can use Paths.get instead Path.of You need also to check if the parent folder does not exist.

CodePudding user response:

Check if the file exists in the constructor itself. Update the private constructor of DataCenter like below.

private DataCenter() {
   if (instance != null) {
      throw new Error();
   }
   // create the file if it doesn't exist already.
   if(!Files.exists(Path.of(filename)){
        Files.createDirectories(Path.of("<PARENT-FOLDER"));
        Files.createFile(Path.of(filename)) 
   }
   file = new File(filename);
  }
  • Related