【发布时间】:2021-04-29 01:02:36
【问题描述】:
我已经编写了这段代码,在对文件中的内容进行哈希处理后首先从文件中读取。它将写入原始内容和哈希值。但是当我尝试运行该程序时,该程序将继续编写并且不会停止。我的代码有什么问题?
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();
}
}
【问题讨论】:
-
不要同时打开同一个文件的多个流。它们会相互干扰,并且可能会弄乱一切,例如由于缓冲和类似的效果。完全读取文件,关闭流,进行编辑,然后完全写回。此外,请使用 try-with-resources 以确保不会出现资源泄漏。