0

到目前为止我所拥有的:

  • 获取用户名和密码并将其写入文本文件的代码块。

    String usernameFilename;    
    usernameFilename = newUsernameField.getText();
    char[] signupPassword = newPasswordField.getPassword();
    String writePassword = new String(signupPassword);
    
    try {
        FileWriter userInfoWriter = new FileWriter(usernameFilename);
        BufferedWriter writeToFile = new BufferedWriter(userInfoWriter);   
        writeToFile.write(usernameFilename);  
        writeToFile.write("\r\n" + writePassword);
        writeToFile.close();
    

我需要完成的事情:

  • 创建一个目录到一个名为users.
  • 将文件保存usernameFilename到目录。

我试过的:

  • 我在网上到处搜索!我找不到任何东西可以做到这一点:c

额外信息:由于所有计算机都不同,我想.getAbsolutePath()在创建目录时使用该方法。

4

1 回答 1

0

看一眼:

你可以更新你的代码看起来更像这个......

String usernameFilename;    
usernameFilename = newUsernameField.getText();
char[] signupPassword = newPasswordField.getPassword();
String writePassword = new String(signupPassword);

File users = new File("users");
if ((users.exists() && users.isDirectory()) || users.mkdirs()) {

    FileWriter userInfoWriter = null;
    BufferedWriter writeToFile = null;
    try {
        userInfoWriter = new FileWriter(users.getPath() + File.seperator + usernameFilename);
        writeToFile = new BufferedWriter(userInfoWriter);   
        writeToFile.write(usernameFilename);  
                    writeToFile.newLine();
        writeToFile.write(writePassword);

        //....
    } finally {
        try {
            writeToFile.close();
        } catch (Exception exp) {
        }

    }

} else {
    throw new IOException("Could not create/find Users directory");
}
于 2013-04-29T00:40:31.413 回答