嘿,我正在做一个学校项目,正在尝试编写问题库。我正在使用一个JFrame,它允许用户输入数据。然后,我想将数据存储在txt文件中,以便以后可以检索它。我在将其添加到问题库中时遇到麻烦。关于如何删除某个“问题”的任何提示?。
例如,如果我想从以下文件中删除数学问题:
Geography_What is England's capital_Berlin_Manchester_Dover_London_D_3
Maths_What is 2+3_7_9_5_6_C_1
Economics_What is demand_idk_stuff_demand_supply_C_2
删除
String topic = Topic.getSelectedItem().toString();
String question = Question.getText();
String a = AnswerA.getText();
String b = AnswerB.getText();
String c = AnswerC.getText();
String d = AnswerD.getText();
String answer =Correct.getText();
String credit =Points.getText();
String remove = topic + "_" + question + "_" + a + "_" + b + "_" + c + "_" + d + "_" + answer + "_" + credit;
File inputFile = new File("Questions.txt");
File tempFile = new File("QuestionsTemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = remove;
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
try {
writer.write(currentLine + System.getProperty("line.separator"));
} catch (IOException ex) {
Logger.getLogger(QuestionBank.class.getName()).log(Level.SEVERE, null, ex);
}
}
try {
inputFile.delete();
reader.close();
writer.close();
inputFile.delete();
boolean successful = tempFile.renameTo(inputFile);
System.out.println(successful);
}
catch (IOException ex) {
ex.printStackTrace();
}
添加
String topic = Topic.getSelectedItem().toString();
String question = Question.getText();
String a = AnswerA.getText();
String b = AnswerB.getText();
String c = AnswerC.getText();
String d = AnswerD.getText();
String answer =Correct.getText();
String credit =Points.getText();
String answerPos = "AaBbCcDd";
String scorePos = "12345";
try{
FileWriter writer = new FileWriter("Questions.txt", true);
writer.write(System.getProperty("line.separator"));
writer.write(topic);
writer.write("_");
writer.write(question);
writer.write("_");
writer.write(a);
writer.write("_");
writer.write(b);
writer.write("_");
writer.write(c);
writer.write("_");
writer.write(d);
writer.write("_");
writer.write(answer);
writer.write("_");
writer.write(credit);
writer.close();
JOptionPane.showMessageDialog(rootPane, "Success");
}
catch(HeadlessException | IOException e){
JOptionPane.showMessageDialog(rootPane, "Error");
}
}
答案 0 :(得分:0)
我建议您使用序列化库来保存诸如Gson之类的对象。然后,您可以更轻松地管理保存和加载。或使用CSV或XML等标准格式。