我想将编辑文本的值与文件中的所有行进行比较。(文件是单词列表)
我已经这样做了,
try{
final InputStream file = getAssets().open("words.txt");
reader = new BufferedReader(new InputStreamReader(file));
String line = reader.readLine();
while(line != null){
line = reader.readLine();
if(ss == line.toLowerCase()){
Toast.makeText(this, "Working!", Toast.LENGTH_SHORT)
.show();
}
else{
Toast.makeText(this, "Not found !", Toast.LENGTH_SHORT)
.show();
}
}
} catch(IOException ioe){
ioe.printStackTrace();
}
这里ss是textfield的值。
String ss = (res.getText()).toString();
这是word .txt文件https://raw.githubusercontent.com/eneko/data-repository/master/data/words.txt
但是上面的代码不起作用
编辑:我检查了文件是否正在打开,问题是文件没有打开。
try{
final InputStream file = getAssets().open("words.txt");
Toast.makeText(this, "File Opened", Toast.LENGTH_SHORT)
.show();
reader = new BufferedReader(new InputStreamReader(file));
String line ;
while((line = reader.readLine()) != null){
if(ss.equalsIgnoreCase(line)){
Toast.makeText(this, "Working!", Toast.LENGTH_SHORT)
.show();
TextView tv = myTextViewList.get(counter);
tv.setText(line);
}
else{
Toast.makeText(this, "Not found !", Toast.LENGTH_SHORT)
.show();
}
}
} catch(IOException ioe){
ioe.printStackTrace();
}
试试这个
ss.equalsIgnoreCase(line.toLowerCase())
将" ==
"替换为" equalsIgnoreCase
"或" equals
"
您读取了两行,并使用equalsIgnoreCase来比较字符串
while((line = reader.readLine()) != null){
if(ss.equalsIgnoreCase(line)){
Toast.makeText(this, "Working!", Toast.LENGTH_SHORT)
.show();
}
else{
Toast.makeText(this, "Not found !", Toast.LENGTH_SHORT)
.show();
}
}
试试这个…
BufferedReader in = new BufferedReader(new FileReader(filepath));
boolean found = false;
while (( line = in.readLine()) != null)
{
if (line.contains(str))
{
found = true;
break; //break out of loop now
}
}
in.close();
if (found)
{
System.out.println("Yes");
}
else
{
System.out.println("No");
BufferedWriter out = new BufferedWriter(new FileWriter(filepath,true));
out.newLine();
out.write(str);
out.close();
}
在你的代码中,它不断地逐行比较,直到它到达你的最后一行(即235886),它将在循环中连续运行。它会逐一检查所有行,所以当你第一次比较时,如果成功,就会打破循环,同时使用。equals进行字符串比较而不是'=='
String ss = "a";
try{
final InputStream file = getAssets().open("words.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
String line = reader.readLine();
while(line != null){
line = reader.readLine();
if(ss.equals(line)){
Toast.makeText(this, "Working!", Toast.LENGTH_SHORT)
.show();
break;
}
else{
Toast.makeText(this, "Not found !", Toast.LENGTH_SHORT)
.show();
break;
}
}
} catch(IOException ioe){
ioe.printStackTrace();
}