2017-06-18 65 views
0

该文件夹的根创建是我希望它成为的方式,使这很好。该方法还创建文件和文件夹,但我不知道如何让它在文件夹中创建。创建一个文件夹和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(); 
    } 
} 

回答

0

你已经把管理作为路径之前文件名一样,

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(); 
} 
0
  1. 我觉得这是更好地避免使用AWT组件,如文本字段在你的程序中。改为使用轻量级Swing组件,如JTextField和JPasswordField。
  2. 通过使用文件分割符,而不是你保证,如果你曾经它移植到另一种操作环境你的程序也将无法正常运行反斜杠。
  3. JPasswordField有一个.getPassword()方法,它返回一个字符数组。您可以直接在您的BufferedWriter写入方法中使用它。你甚至可以将它转换为一个String ps = new String(pass.getPassword());.
  4. 它始终是更好地关闭您的文件中finally块,因为如果发生IOException,它会跳过bw.close()方法调用,你的文件将被悬空。
  5. e.printStackTrace()是一个快速和肮脏的溶液。避免使用它,因为它会写入stderr,并且输出可能会丢失。阅读God's Perfect Exception,以了解上帝在创世纪时是如何做到的。使用日志框架。 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 
         } 
        } 
    }