【问题标题】:BufferedWriter is not workingBufferedWriter 不工作
【发布时间】:2016-02-06 07:27:21
【问题描述】:

所以我正在编写代码,作为一种用于登录系统的文件系统,预先添加了两个帐户,两个帐户都是管理员。他们可以创建帐户。所有帐户都存储在其用户名的数组列表和密码的数组列表中。我正在尝试这样做,以便当我导出此应用程序时,当管理员添加到数组列表时,会将信息发送到 txt 文件,以便下次运行程序时,程序将加载任何帐户txt 文件。我已经测试了帐户的加载,效果很好,但我似乎无法写入 txt 文件。我从这个站点以这种方法获取了这段代码,但我不确定我做错了什么:

public static void writeFileContnet(){
    String path = "C:\\Users\\DJANDEK\\Desktop\\LogInPro\\info.txt";
    BufferedWriter writer = null;

    try {
        writer = new BufferedWriter(new FileWriter(path, true));
        if(!loadFileAsString(path).equals("")){
            writer.newLine();
        }
        System.out.println(Account.accounts.get(Account.accounts.size()-1));
        writer.write(Account.accounts.get(Account.accounts.size()-1));

        System.out.println(breaker);
        writer.write(breaker);

        System.out.println(Account.passwords.get(Account.passwords.size()-1));
        writer.write(Account.passwords.get(Account.passwords.size()-1));

        writer.write(breaker);

    } catch (IOException e) {
        e.printStackTrace();
    }

    BufferedReader in = null;
    try {
        in = new BufferedReader(new FileReader(path));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    String line;
    try {
        while((line = in.readLine()) != null)
        {
            System.out.println("it prints this");
            System.out.println(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

对于那些想知道 println 的人,控制台显示: 鲍勃; 1Q2W; BobsPass (信息正确)。 我在控制台中没有错误。为了回答重复的问题,他被告知使用文件,而不是如何使用文件。如果我的 txt 文件中已经有数据,Reader 会读取并 s.o.p 它。

【问题讨论】:

标签: java file bufferedreader bufferedwriter


【解决方案1】:

您无法写入 jar 中的文件。您需要提供文件系统上文件的路径。

【讨论】:

  • 好的,我不确定,但我认为这会是个问题。我之前确实尝试过,但由于某种原因,路径无法正常工作。我尝试了这条路径: C:\\Users\\DJANDEK\\Desktop\\LogInPro\\info.txt 但这似乎不起作用。我需要做一些关于绝对路径的事情吗?
  • 我确实修复了路径问题(我一定不能拼写,因为它现在可以正常工作了),但它似乎仍然没有写出来。如果我在文件中有文本,它仍然会读取它,但似乎没有添加其他文本。
  • @Deek,还有另一个错误 - 你没有关闭 BufferedWriter。我为此添加了第二个答案。
【解决方案2】:

即使您更改为使用文件系统中的文件而不是 jar 中的文件,它仍然不会写入文件,因为您没有关闭 BufferedWriter。

您可以像 BufferedReader 一样显式关闭它。或者更好的是,您可以使用try-with-resources

【讨论】:

  • 这成功了!感谢您的帮助,我仍然会查看您的链接:)
猜你喜欢
  • 2013-01-05
  • 1970-01-01
  • 2015-07-07
  • 1970-01-01
  • 1970-01-01
  • 2018-08-26
  • 2014-07-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多