2017-06-18 67 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 
         } 
        } 
    }