'Read and Write to the same text file
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();
}
}
Solution 1:[1]
You specified true as the append argument of FileWriters constructor. So you are probalby reading what you previously written into the file.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ackdari |
