天天看点

java 防止文件重名的方法_使用java避免文本文件中的重复输出?

我有一个简单的问题。

我有一个文本文件,其中包含以下记录:

HAMADA 115599

KARIM 224466

BOSY 47896512

此文件实际上定义了用户帐户的用户名和密码

现在我写了一个简单的代码来编辑特定用户的密码。

这是我的代码:

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import java.util.Objects;

import java.util.Scanner;

public class Test6 {

public static void main(String[] args)throws IOException {

String newPassword=null;

boolean checked = true;

File f= new File("C:\\Users\\فاطمة\\Downloads\\accounts.txt");// path to your file

File tempFile = new File("C:\\Users\\فاطمة\\Downloads\\accounts2.txt"); // create a temp file in same path

BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

Scanner sc = new Scanner(f);

System.out.println("Change account password !!");

System.out.println("Validate your account please !!");

System.out.printf("Username: ");

Scanner sc2 = new Scanner(System.in);

String username = sc2.next().toUpperCase();

System.out.printf("Old Password: ");

String password = sc2.next();

while(sc.hasNextLine())

{

String currentLine= sc.nextLine();

String[] tokens = currentLine.split(" ");

if(Objects.equals(tokens[0], username) && Objects.equals(tokens[1], password) && checked)

{

sc2.nextLine();

System.out.printf("New Password: ");

newPassword= sc2.nextLine();

if(newPassword.length() >= 6)

{

currentLine = tokens[0]+" "+newPassword;

checked = false;

}

else

System.out.println("Short Password, Password must be at least 6 characters.");

}

else{System.out.println("Wrong username or password .. try again !!");}

writer.write(currentLine + System.getProperty("line.separator"));

}

writer.close();

sc.close();

f.delete();

boolean successful = tempFile.renameTo(f);

if(successful == true)

System.out.println("Your password has been changed successfully.");

else

System.out.println("Error occurred during changing password, please try again.");

}

}

问题是:如果我在文件中有如上所述的许多记录,现在它将为每个记录停止写入“错误的用户名或密码”消息。我只是想让程序只在输入的记录中说这个消息,然后在程序中停止。如果在文件中找到记录,则允许用户更改该记录的密码