我想要做的是用戶選擇後從組合框項目,點擊一個按鈕,案例2將運行,並且將txtcp文本框設置爲RK1314,並將其保存到文本文件Java:爲什麼我無法讀取和比較文本文件?
case 2: if (sportcb.getSelectedItem().equals("Ferrari F430 Scuderia"))
{
...
txtcp.setText("RK1314");
所以在按下按鈕之後,我想要讀取和比較文本,如果它出現在文本文件中,則會出現消息。
String line;
String fileName = "test.txt";
String link = txtcp.getText();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(fileName));
while((line=br.readLine()) != null) {
if(line.equals(link))
JOptionPane.showMessageDialog(this," identical match found in the text file!");
}
br.close();
}
catch(IOException e) {
JOptionPane.showMessageDialog(this,"hello");
}
這裏是我寫的文本文件代碼:
File data = new File("test.txt");
try {
String cname = name.getText();
String sdate = startdate.getDate().toString();
String edate = enddate.getDate().toString();
if (data.exists() == false) {
System.out.println("We had to make a new file.");
data.createNewFile();
}
PrintWriter out = new PrintWriter(new FileWriter(data, true));
out.append("Customer name: "+cname);
out.append(System.lineSeparator());
out.append("Contact Number: "+cn);
out.append("Car plate: "+plate);
out.append(System.lineSeparator());
out.append("---------------------------------------------------------------------------------------------------------------------");
out.append(System.lineSeparator());
JOptionPane.showMessageDialog(this, "Order is Recorded!");
out.close();
} catch(IOException e) {
JOptionPane.showMessageDialog(this, "Order is not Recorded!");
}
按下按鈕後,什麼都沒有發生。
我試過使用FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(f r); 但它仍然不會工作 – user63566
pl編輯您的問題,並添加評論中添加的信息到您的問題文本並刪除評論。 –
@RajenRaiyarela基本上沒什麼,我只是嘗試了一種不同的方式,但最後結果仍然是一樣的 – user63566