java - 无法将字符串写入 FileWriter/BufferedWriter

标签 java google-authenticator

我正在尝试创建一个应用程序来创建 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/

相关文章:

java - JTextPane 不会换行

java - 在多模块 maven 项目中的模块之间共享 src/test 类

javascript - 安全错误 - 该页面包含来自第三方域的一个或多个脚本文件

python - 生成的代码与 PyOTP 示例不匹配

android - 谷歌验证器刮刮码

ios - iOS 应用程序是否可以与 Google Authenticator 通信?

python - Google oAuth 2.0 API 身份验证错误 : Error 400 - redirect_uri_mismatch (does not comply with policy) DJANGO APP

java - 在 Spring Boot 测试中正确使用 TestPropertyValues

java - n :m Relation with additional Information in Hibernate

java - 如何使用java创建远程桌面访问应用程序?