Search code examples
javafilecreatefile

Java: createUser Constructor fails to create a file?


I've just learned to create and read from files and I'm practicing it by making a little program. The problem is that my constructor is unable to create the file that I need.

Here is my main:

  public static void main(String[] args) {

    createUser user = new createUser("username", "password");  

    }

Here is my class:

public class createUser {

private Formatter formatter;
private Scanner scanner;
private File file;
private String username;
private String password;

createUser(String username, String password){
    this.username = username;
    this.password = password;
try{
    String path = "D:\\Users\\" + this.username +".txt";
    file = new File(path);
    formatter = new Formatter(path);                    
    scanner = new Scanner(new File(path));
    formatter.format("Username: %s\n", username);
    formatter.format("Password: %s\n", password);
    formatter.close();
    System.out.printf("%s has been created!", this.username);
}
catch(Exception e){
    System.out.println("Failed to create the account!");
}

}

}

Output: Failed to create the account!


Solution

  • It turned out that I have to create the Users folder manually.