【发布时间】:2016-05-03 01:59:54
【问题描述】:
在一个随机生成的密码文件中,我的目标是要求输入密码,检查“codes.txt”文件是否存在,说“登录完成”5 秒钟,删除密码,然后关闭文件.当我到达 while 循环时,我没有按我需要的方式工作。它在各种情况下都有各种不同的结果,我都无法理解。我什至还没有弄清楚如何在打印“登录完成”5 秒后删除控制台上的内容。如果有人现在可以帮助我,我将不胜感激。我的代码位于下面。
package password;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;
public class Password {
public void creator() throws IOException {
FileWriter fw = new FileWriter(new File("codes.txt"));
PrintWriter out = new PrintWriter(fw);
char[] chars = "abcdefghijklmnopqrstuvwxyz1234567890".toCharArray();
Random random = new Random();
for (int x = 0; x < 51; x++){
String word = "";
for (int i = 0; i <= 10; i++) {
char c = chars[random.nextInt(chars.length)];
word+=c;
}
out.println(word);
}
fw.close();
}
public void readit() throws FileNotFoundException, InterruptedException {
File file = new File("codes.txt");
Scanner input = new Scanner(file);
//prints each line in the file
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
Thread.sleep(10000);
input.close();
}
public void checkit() throws FileNotFoundException, IOException, InterruptedException {
File checkFile = new File("codes.txt");
File tempFile = new File("tempFile.txt");
Scanner input = new Scanner(System.in);
Scanner reader = new Scanner(checkFile);
FileWriter fw = new FileWriter(tempFile);
PrintWriter out = new PrintWriter(fw);
System.out.println("What is the password?");
String word = input.nextLine();
while(reader.hasNextLine()) {
String line = input.nextLine();
if(line.equals(word)){
System.out.println("LOGIN COMPLETE");
Thread.sleep(5000);
} else {
out.println(line);
}
}
reader.close();
fw.close();
checkFile.delete();
tempFile.renameTo(checkFile);
}
}
主文件如下。
package password;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException, FileNotFoundException, InterruptedException {
Password pass = new Password();
pass.creator();
pass.readit();
pass.checkit();
}
}
我是java初学者,所以为了让我理解代码,请使用简单的初学者代码。
【问题讨论】:
-
如何删除控制台上的内容将取决于控制台。
-
I haven't even figured out how to delete the stuff on the console after 5 seconds这甚至都不是微不足道的。你应该使用诅咒之类的吗?从控制台删除内容不是标准操作。 -
如果不清楚,我只需要清除 System.out.println 给出的输出信息
标签: java file filewriter printwriter