天天看點

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.");

}

}

問題是:如果我在檔案中有如上所述的許多記錄,現在它将為每個記錄停止寫入“錯誤的使用者名或密碼”消息。我隻是想讓程式隻在輸入的記錄中說這個消息,然後在程式中停止。如果在檔案中找到記錄,則允許使用者更改該記錄的密碼