最近已经从Java中的文件中测试了一种密钥验证代码。我仍然是这个(IO)的新手,在网上看到无穷无尽的方法来接近这个,但我无法区分各种专业人士和这些方法之间的缺点。我想提出我的代码并问我应该如何正确处理,它有效,但我并不是太满意。
我知道大多数人反对以建议为导向的问题,如果是这样的话,我很乐意把这个话题放下来,只是想事先要求一些帮助。谢谢
/*
* To be able to give you a rundown of the situation:
* Inside my project file I have a .txt file named 'MasterKey'
* Initially inside this file is a key and validation boolean 'false'
* On start-up the program analyzes this file, if it detecs a key it then
* Asks the user to input the key. If it is valid it then creates/overwrites the
* Previous file with a new .txt with same name but only "true" is inside it.
* If the key is incorrect, it will continue requesting for the key
*/
import java.io.*;
import java.util.Scanner;
public class MasterKeyValidationTest {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
getFileInfo(); //Method below
}
private static void getFileInfo(){
File readFile = new File("/Users/Juxhin's Lab/Desktop/Projects/MasterKey.txt"); //My file directory
try{
BufferedReader getInfo = new BufferedReader(
new FileReader(readFile));
String fileInfo = getInfo.readLine(); //Gets the key or 'true'
if(fileInfo.contains("true")){ //If file contains 'true', program is valid
System.out.println("Valid");
}else{
System.out.println("Enter Key");
String key = input.next(); //Receive input for the key
if(!fileInfo.contains(key)) { //If the file doesn't contain the key you just entered
System.out.println("Invalid key");
key = input.next(); //Receive another key input
getFileInfo(); //Start the method from top again to check
}
if (fileInfo.contains(key)) { //If the file contains the key you just entered
System.out.println("Program valid");
FileWriter fstream = new FileWriter("/Users/Juxhin's Lab/Desktop/Projects/MasterKey.txt"); //Create/Overwrite the MasterKey.txt file
BufferedWriter out = new BufferedWriter(fstream);
out.write("true"); //Input "true" inside the new file
out.close(); //Close the stream
}
}
}catch(FileNotFoundException e){
System.out.println("File not found");
System.exit(0);
}catch(IOException e){
System.out.println("An IO Error");
System.exit(0);
}
}
}
答案 0 :(得分:2)
一些建议..
1. String fileInfo = getInfo.readLine(); //Gets the key or 'true' .. reads only 1 line (if that is what you want..)
2. use fileInfo =fileInfo.trim() // to remove leading and trailing whitespaces.
3. If you just want to "read" the file, use FileReader, BufferedReader. If you want to "parse" the file, use a Scanner.