Answer the question
In order to leave comments, you need to log in
How to compare a variable with each line of a file?
I need to compare each line in the file and find matches, if there is a match, set flagNameStr - to value 1. I tried like this, but somehow it does not work, please help.
private byte flagNameStr = 1;
private String myTxt = "Gg";
try {
FileInputStream fileInput = openFileInput("file.txt");
InputStreamReader readerlist = new InputStreamReader(fileInput);
BufferedReader bufferlist = new BufferedReader(readerlist);
StringBuffer strBuffer = new StringBuffer();
String lines;
while ((lines = bufferlist.readLine()) != myTxt && (lines = bufferlist.readLine()) != null){
flagNameStr = 1;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Answer the question
In order to leave comments, you need to log in
You need to use equals() to compare strings.
Rewrite the while loop - it looks bad.
Better would be something like
while (lines = bufferlist.readLine()){
if (lines.equals(myTxt)) {
flagNameStr = 1;
break;
}
}
// В 21 веке живём, и Java Streams под рукой, и try-with-resources тоже...
try (BufferedReader reader = Files.newBufferedReader(Paths.get("file.txt"))) {
reader.lines().anyMatch(line -> {
if (myTxt.equals(line)) {
flagNameStr = 1;
return true;
}
return false;
});
} catch (FileNotFoundException | IOException ex) {
ex.printStackTrace();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question