Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

java - 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();
    } 
}
question from:https://stackoverflow.com/questions/65881127/read-and-write-to-the-same-text-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to reply this article.

OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...