【问题标题】:reading and writing data with a text file in java在java中使用文本文件读取和写入数据
【发布时间】:2015-03-14 05:02:07
【问题描述】:

我正在尝试创建一个命令,允许登录的用户编辑他们的用户名和密码,然后保存更新的详细信息。目前更新详细信息似乎有效,但是当我将详细信息写入新文件时,旧文件中的所有其他数据(其他用户详细信息)都将被删除,并且只有当前用户更新的详细信息出现在文件中。这是我的代码:

public class UpdateDetailsCommand implements Command{
private BufferedWriter out;
private BufferedReader in;
private MsgSvrConnection conn;

public void execute() throws IOException
  {

    if (conn.getCurrentUser() != null) {

        String username1 = conn.getCurrentUser();
        String password1 = conn.getServer().getUserPassword(username1);

        BufferedReader fr = new BufferedReader(new FileReader("pwd.txt"));
        PrintWriter fw = new PrintWriter(new FileWriter("pwd.txt", true));
        String line;

        String username = in.readLine();
        String password = in.readLine();

        if (password != null && username != null)   {

            while ((line = fr.readLine()) != null) {
            if (line.contains(username1) && line.contains(password1) ){
                    line = line.replace(username1, username);   
                    line = line.replace(password1, password);
    fw.println(line);
}           
}
                fr.close();
                fw.close();


                out.write("done");  
                out.flush();
            }

        }

    }

public  UpdateDetailsCommand(BufferedReader in, BufferedWriter out, 
          MsgSvrConnection serverConn)
{
this.out = out;
this.in = in;
this.conn = serverConn;

} }

我猜我读写文件的方式不太正确,但我不确定我在这里做错了什么。

【问题讨论】:

  • 你没有检查.delete().renameTo()的结果...不是你的问题,但他们可能会失败。

标签: java database file server


【解决方案1】:

如果要编写文本文件(行结构),请使用 PrintWriter。

PrintWriter fw = new PrintWriter( new FileWriter("temp_pwd.txt", true) );

while 循环不能包含 close() - 这会终止一切。

while ((line = fr.readLine()) != null) {
            if (line.contains(username1))
                line = line.replace(username1, username);
            if (line.contains(password1))
                line = line.replace(password1, password);
            fw.println(line);
} // close while block here

fr.close();
fw.close();

您还应该确保只更改一行。密码多次出现的可能性很小,但有可能。

   if (line.contains(username1) && line.contains(password1) ){
        line = line.replace(username1, username);   
        line = line.replace(password1, password);
   }

此外, contains() 不是一个好的测试方法。如果你有一个用户怎么办

   josephus,Oki987e3

还有一个

   joseph,Oki987e3

约瑟夫更改了他的用户名和密码??

【讨论】:

  • 谢谢,我进行了更改,现在它似乎保存了数据,但它将所有数据保存在一行中,没有空格,因此我无法读取用户名和密码。 pwd 文件的结构方式是每个用户名和密码都存储在一个新行上,格式为 username=password (“=”目前正在正确添加)。
  • 推荐使用 PrintWriter。不要尝试手动编写行尾。 - 查看答案中的更新。
  • 另外,close() 调用应该在 finally 块中。
  • @DavidConrad 还有尝试/资源等等。
  • @laune 我已经进行了进一步的更改(更新了帖子),它现在写入每一行。我现在遇到的问题是,我尝试将第二行“red = bean”更新为“red = Bean”,当文件更新时我得到以下结果“red = beanred = Bean”所以看起来已将输入添加到旧数据中并且没有替换它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-06
  • 1970-01-01
  • 1970-01-01
  • 2014-03-20
  • 2013-03-25
  • 1970-01-01
相关资源
最近更新 更多