Java: createUser 构造函数创建文件失败?
Java: createUser Constructor fails to create a file?
我刚刚学会了创建和读取文件,我正在通过制作一个小程序来练习它。问题是我的构造函数无法创建我需要的文件。
这是我的主要内容:
public static void main(String[] args) {
createUser user = new createUser("username", "password");
}
这是我的 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!");
}
}
}
输出:
创建账号失败!
原来我必须手动创建 Users 文件夹。
我刚刚学会了创建和读取文件,我正在通过制作一个小程序来练习它。问题是我的构造函数无法创建我需要的文件。
这是我的主要内容:
public static void main(String[] args) {
createUser user = new createUser("username", "password");
}
这是我的 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!");
}
}
}
输出: 创建账号失败!
原来我必须手动创建 Users 文件夹。