Java:为什么我无法读取和比较文本文件?
我想要做的是用户选择后从组合框项目,点击一个按钮,案例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!");
}
按下按钮后,什么都没有发生。
您的代码似乎在寻找一条等于“RK1234”的线条;即
if (line.equals(link)) { ...
然而,用于写入文件的代码输出该数据是这样的:
out.append("Customer name: "+cname);
out.append(System.lineSeparator());
out.append("Contact Number: "+cn);
out.append(System.lineSeparator());
out.append("Car plate: "+plate); // Updated ...
out.append(System.lineSeparator());
out.append("---------------------------------------" +
"---------------------------------------" +
"---------------------------------------");
out.append(System.lineSeparator());
的4行中没有通过上述生产可可能等于“RK1234”。假设RK1234是“板”,那么该线将是“车牌:RK1234”......这不等于“RK1234”。
所以,当你按下按钮:
- 它打开文件。
- 它读取每一行都没有匹配(所以没有对话框)
- 它不会抛出I/O异常(所以没有“你好”)对话框。
- 它到达文件末尾,关闭它并完成。
总之,你不要看到任何对话框。
也许你应该测试如果一行包含那个字符串;例如
if (line.indexOf(link) >= 0) { ...
或
if (line.contains(link)) { ...
非常感谢您指出我的问题,我重新编辑了这些问题。 – user63566
即使在对问题进行编辑之后,我的答案仍然存在。 –
可能的原因是您的文件没有写入。
根据PrintWriterPrintWriter(Writer)构造函数创建一个新的PrintWriter,不会自动行刷新。因此,无论您需要在out.close()
之前致电out.flush()
还是创建PrintWriter使用this控制器,您可以使用该控制器指定autoFlush参数的“true”。
目前发生的事情是您的文件没有被写入。
这是不正确的。 'out.close()'会在关闭之前刷新所有数据。如果它不能,它会抛出一个异常。 http://docs.oracle.com/javase/8/docs/api/java/io/OutputStreamWriter.html#close-- –
根据你的问题。该文件包含这样的权利。 客户名称:宝贝 客户编号:1234 订单编号:RK123。 所以,当你正在阅读文件 它正在逐行阅读 。所以请不要使用equals方法。使用包含方法。它会给你结果。
我试过使用FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(f r); 但它仍然不会工作 – user63566
pl编辑您的问题,并添加评论中添加的信息到您的问题文本并删除评论。 –
@RajenRaiyarela基本上没什么,我只是尝试了一种不同的方式,但最后结果仍然是一样的 – user63566