H
H
Helig2018-08-08 11:01:00
Java
Helig, 2018-08-08 11:01:00

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

2 answer(s)
E
EVGENY T., 2018-08-08
@Helig

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;
   }
}

Well, the flag must be reset depending on what you need to check: the presence in at least one line from the file or the presence in each line.

R
roswell, 2018-08-08
@roswell

// В 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 question

Ask a Question

731 491 924 answers to any question