gpt4 book ai didi

java - 需要文件覆盖/读取建议

转载 作者:行者123 更新时间:2023-12-02 05:47:46 25 4
gpt4 key购买 nike

最近去测试了一种来自Java文件的 key 验证代码。我对此(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);
}
}

}

最佳答案

一些建议..

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.

关于java - 需要文件覆盖/读取建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23887660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com