我正在用 Java 做我的论文。我被困在某一点上。我无法让工作从文件中搜索字符串。我需要从文件中搜索用户输入的单词,即使文件中的字符串是“F”并且他输入“f”我也必须得到响应。做到这一点的最佳方法是什么?这是实现这种目标的最佳方式吗?如果我错了,也许最好使用 ArrayList 来纠正我。
这是我到目前为止所做的:
JButton btnTuletaParoolMeelde = new JButton("Tuleta parool meelde");
btnTuletaParoolMeelde.setBackground(new Color(37, 209, 175));
btnTuletaParoolMeelde.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Search
String keskkond = textArea.getText();
if(keskkond.length()<=0){
System.out.println("You didn't enter anything");
}else{
int tokencount;
FileReader filereader = null;
try {
filereader = new FileReader("paroolid.txt");
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
BufferedReader br=new BufferedReader(filereader);
String s;
int linecount=0;
String keyword = keskkond; //keskkond is like Facebook etc..
try {
while ((s = br.readLine())!=null){
if(s.contains(keyword))
System.out.println(s);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
这是人们可以输入网络和密码的地方,然后它将其写入文件。
//Add your password and network and Button actions
btnLisaParool = new JButton("Add passowrd");
btnLisaParool.setBackground(new Color(37, 209, 175));
btnLisaParool.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String parool = String.valueOf(passwordField.getPassword());
String koht = textField.getText();
if (koht.isEmpty() && parool.isEmpty()) {
lblFeedback.setText("You didn't enter anything.");
} else if(parool.isEmpty()) {
lblFeedback.setText("Enter password please!.");
}else if(koht.isEmpty()){
lblFeedback.setText("Enter network please!");
}else{
FileWriter fWriter = null;
BufferedWriter writer = null;
try {
fWriter = new FileWriter("paroolid.txt", true);
writer = new BufferedWriter(fWriter);
writer.write("Teie " + koht + " -i parool oli: " + parool);
writer.newLine();
writer.close();
lblFeedback.setText("Teie " + koht + " parool, mis koosnes " + parool.length() + " tähest, on salvestatud.");
} catch (Exception e1) {
lblFeedback.setText("Error: " + "Couldn't find file");
}
}
passwordField.setText("");
textField.setText("");
}
最佳答案
首先,不要在 EDT
上执行长时间运行的操作(例如读/写文件)。其次,确保释放所有使用的资源以防止内存泄漏。要回答您的问题,您可以将您正在搜索的 String
和正在搜索的字符串修改为小写或大写。
这是一个例子:
try(BufferedReader br = new BufferedReader(new FileReader("paroolid.txt"))){
for(String line; (line = br.readLine()) != null;){
if(line.toLowerCase().contains(toSearchFor.toLowerCase())){
System.out.println(line);
}
}
}catch(Exception e){
e.printStackTrace();
}
关于java - 从文本文件中搜索字符串(不区分大小写),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36519015/