创建一个文件夹并将 txt 文件写入其中以创建注册方法 (Java)



在根目录中创建的文件夹是我希望它的方式,所以这很好。该方法还可以很好地创建文件和文件夹,但我不知道如何在文件夹中创建它。

这是我到目前为止所拥有的:

public void registration(TextField user, PasswordField pass){
File admin = new File("adminstrator");
if(!admin.exists()){
admin.mkdir();
}
//add some way to save file to admin folder
try (BufferedWriter bw = new BufferedWriter(new FileWriter("USER_PASS.txt", true))){
bw.write(user.getText());
bw.newLine();
bw.write(pass.getText());
bw.newLine();
bw.close();
}
catch(IOException e){
e.printStackTrace();
}
}

您将 admin 作为文件名之前的路径,如下所示

try (BufferedWriter bw = new BufferedWriter(new FileWriter(admin + "\USER_PASS.txt", true))){
bw.write(user.getText());
bw.newLine();
bw.write(pass.getText());
bw.newLine();
bw.close();
}
catch(IOException e){
e.printStackTrace();
}
  1. 我认为最好避免在程序中使用TextField等AWT组件。改用轻量级的 Swing 组件,如 JTextField 和 JPasswordField。
  2. 通过使用File.separator而不是反斜杠,可以确保程序在移植到另一个操作环境时也能正常运行。
  3. JPasswordField 有一个 .getPassword() 方法,它返回一个字符数组。您可以直接在 BufferedWriter 写入方法中使用它。您甚至可以将其转换为字符串ps = new String(pass.getPassword());。
  4. 最好在
  5. finally 块中关闭文件,因为如果发生 IOException,它将跳过 bw.close() 方法调用,并且您的文件将保持打开状态。
  6. e.printStackTrace() 是一个快速而肮脏的解决方案。避免使用它,因为它写入 stderr,输出可能会丢失。阅读上帝的完美例外,以了解上帝在创世记期间是如何做到的。使用日志记录框架。SLF4J是一个不错的选择。

    public void registration(JTextField user, JPasswordField pass) {  // 1
    File admin = new File("adminstrator");
    BufferedWriter bw = null;
    if (!admin.exists()) {
    admin.mkdir();
    }
    try {
    bw = new BufferedWriter(new FileWriter(admin + File.separator + "USER_PASS.txt", true)); // 2
    bw.write(user.getText());
    bw.newLine();
    bw.write(pass.getPassword()); // 3          
    bw.newLine();
    } catch (IOException e) {
    e.printStackTrace();  // 5
    } finally { // 4
    try {
    if (bw != null) {
    bw.close();
    }
    } catch (IOException e) {
    e.printStackTrace(); // 5
    }
    }
    }
    

最新更新