如何将文件保存到目录

时间:2013-04-29 00:23:33

标签: java directory text-files

到目前为止我所拥有的:

  • 一段代码,用于输入用户名和密码并将其写入文本文件。

    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()方法。

1 个答案:

答案 0 :(得分: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");
}