2015-11-03 52 views
0

我有记录,有这样一个文本文件:如何使用java编辑文本文件中的记录?

JOHNY 412563 
SARAH 147852369 

这些记录定义的用户名和用户帐户密码。

我写了一个简单的方法来编辑记录的密码。

编辑密码的方式是发送你想编辑的用户名和新密码,然后该方法应该编辑密码。但没有任何反应,它会将新数据复制到临时文件中,但不会再回到主文件。

这里是我写的方法:

public int change_pass(String username, String password) { 

boolean checked = true; 

try { 
    File f = new File("C:\\Users\\فاطمة\\Downloads\\accounts.txt"); 
    File tempFile = new File("C:\\Users\\فاطمة\\Downloads\\accounts2.txt"); 
    BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile)); 

    Scanner sc = new Scanner(f); 
    Scanner sc2 = new Scanner(System.in); 

    while(sc.hasNextLine()) { 
     String currentLine = sc.nextLine(); 
     String[] tokens = currentLine.split(" "); 
     if(Objects.equals(tokens[0], username) && checked) { 
      currentLine = tokens[0]+" "+password; 
      checked = false; 
     } 
     writer.write(currentLine + System.getProperty("line.separator")); 
    } 
    writer.close(); 
    sc.close(); 
    f.delete(); 
    boolean successful = tempFile.renameTo(f); 
    if(successful == true) { 
     return 1; 
    } catch(Exception e) { 
     e.printStackTrace(); 
    } 
    return 0; 
} 

这是我的主要程序我写道:

Scanner sc = new Scanner(System.in); 
String newpass = null; 
System.out.println("Change account password !!"); 
System.out.println("Validate your account please !!"); 
System.out.printf("Username: "); 
a1.setUsername(sc.next().toUpperCase()); 
System.out.printf("Old Password: "); 
a1.setPassword(sc.next()); 

Scanner y = null; 
try{ 
    y = new Scanner(new File("C:\\Users\\?????\\Downloads\\accounts.txt")); 
    boolean checkaccount = false; 
    while(y.hasNext()) { 
     String a = y.next(); 
     String b = y.next(); 
     if((a == null ? a1.getUsername() == null : a.equals(a1.getUsername())) && (b == null ? a1.getPassword() == null : b.equals(a1.getPassword()))) 
      checkaccount = true; 
    } 
    if(checkaccount) { 
     System.out.println("Your account has been verified successfully."); 
    } else 
     System.out.println("Wrong username or password ... try again."); 

    System.out.printf("New Password: "); 
    newpass = sc.next(); 
    if(newpass.length() >= 6) { 
     if(c1.change_pass(a1.getUsername(), newpass) == 1) 
      System.out.println("Password has been changed successfully."); 
     else 
      System.out.println("Error occurred during changing password, try again."); 
    } else 
     System.out.println("Short password: password must be at least 6 characters."); 
} catch(Exception e) { 
    e.printStackTrace(); 
} 
+0

邮报编辑,现在看到的格式。 –

+0

问题是当我在主程序中调用此方法并将用户名和密码传递给它时。它不工作,没有版本发生 –

+0

f.delete()返回布尔值 - 检查它的值。它不可能最有可能移除并且以后不能重命名。 – Rumoku

回答

1

过了许久,我终于找到了我的问题的解决方案:

这很简单:只需添加下面这行:

y.close(); 

前行:

if(checkaccount) 

说明:文件仍处于打开状态,而你试图对其进行编辑。 所以它会给出错误,直到关闭它才能被编辑。

所以你必须在编辑之前关闭文件。

+0

我想知道如何解决这个简单的问题。无论如何感谢你们所有人 –

+1

恭喜你解决它,并且1+以上的答案。你找到它和其他人的原因之一 - 你是唯一一个具有完整功能的可编译代码,可以重现问题。将来,请考虑创建并发布[mcve],以便我们编译/运行/测试/修改/更正代码。 –