2015-10-24 57 views
1

我正在嘗試創建一個將創建Google Authenticator密鑰以及驗證OTP的應用程序。我正在將所有密碼寫入單個文件,並標上與其一起提供的名稱。無法將字符串寫入FileWriter/BufferedWriter

首先,我正在使用這個庫。 https://github.com/aerogear/aerogear-otp-java

這是我的代碼:

public void createUserFile(String name) throws IOException 
{ 
    File file = new File("users\\" + name + ".txt"); 
    file.createNewFile(); 
} 

public void generateUserKey(String name) 
{ 
    try 
    { 
     File file = new File("users\\" + name + ".txt"); 
     FileWriter fw = new FileWriter(file); 
     BufferedWriter out = new BufferedWriter(fw); 
     String s = Base32.random(); 
     out.write(s); 
     out.close(); 
    } 
    catch (IOException e) 
    { 
     e.printStackTrace(); 
    } 
} 

如果我的s值更改爲類似「你好」我很好。但是,它不會寫入隨機字符串。這是我需要幫助的。我修了幾個小時尋找答案,我什麼也沒找到。

+1

'Base32.random()'返回什麼? –

+2

@HovercraftFullOfEels ['Base32'](https://github.com/aerogear/aerogear-otp-java/blob/master/src/main/java/org/jboss/aerogear/security/otp/api/Base32.java ) –

+1

@HovercraftFullOfEels Base32.random返回一個字符串。 –

回答

1

我不相信你需要createUserFile,這是不明確的,你一定知道「用戶/」文件夾(相對路徑)是。我建議你使用System.getProperty(String)來得到user.home用戶主目錄)。

我也建議你使用try-with-resources StatementPrintStream。類似於

public void generateUserKey(String name) { 
    File file = new File(System.getProperty("user.home"), // 
      String.format("%s.txt", name)); 
    try (PrintStream ps = new PrintStream(file)) { 
     ps.print(Base32.random()); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
+0

更清潔。 1+ –

+0

@ElliotFrisch在原始代碼中,它會在程序的根文件夾的目錄。這是做同樣的事情,還是從Windows中的用戶文件夾? –

+0

@JamesDepp您發佈的代碼不會創建目錄。 –