I have written this code to read from the file first after hashing the content from the file. It will write the original content plus hash values. But when I try to run the program the program will keep on writing and won't stop. what is the problem with my code?
package Encrypt;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws Exception {
File file = new File("C:\Users\Tan\Desktop\Test.txt");
Scanner scan = new Scanner(file);
FileWriter writer = new FileWriter("C:\Users\Tan\Desktop\Test.txt", true);
while(scan.hasNextLine()) {
String password = scan.nextLine();
MessageDigest md;
try {
// Select the message digest for the hash computation -> SHA-256
md = MessageDigest.getInstance("SHA-256");
// Generate the random salt
SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);
// Passing the salt to the digest for the computation
//md.update(salt);
// Generate the salted hash
byte[] hashedPassword = md.digest(password.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte b : hashedPassword)
sb.append(String.format("%02x", b));
//Print output
System.out.println(password + " " + sb.toString());
//write output to text file
writer.write(password + " " + sb + System.getProperty("line.separator"));
writer.flush();
}
catch (NoSuchAlgorithmException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
scan.close();
writer.close();
}
}
question from:
https://stackoverflow.com/questions/65881127/read-and-write-to-the-same-text-file 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…