我正在尝试创建一个应用程序来创建 Google Authenticator key 并验证 OTP。我正在将所有密码写入各个文件,并以与其对应的名称为标题。
首先,我正在使用这个库。 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
的值更改为“Hello”之类的值,就可以了。但是,它不会写入该随机字符串。这就是我需要帮助的地方。我已经修补并搜索了几个小时来寻找答案,但我什么也没找到。
最佳答案
我认为您不需要createUserFile
,并且不清楚您是否一定知道“users/”文件夹(相对路径)在哪里。我建议您使用System.getProperty(String)
获取user.home
(用户主目录)。
我还建议您使用try-with-resources
Statement和一个PrintStream
。类似的东西
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();
}
}
关于java - 无法将字符串写入 FileWriter/BufferedWriter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33313717/