-1

I'm using the code below to compare two file input streams and compare them:

        java.util.Scanner scInput1 = new java.util.Scanner(InputStream1);
        java.util.Scanner scInput2  = new java.util.Scanner(InputStream2);

        while (scInput1 .hasNext() && scInput2.hasNext())
        {
         // do some stuff
         // output line number of InputStream1 
         }
       scInput1.close();
       scInput2.close();

How can I output the line number inside the while loop?

van
  • 9,159
  • 19
  • 60
  • 93

1 Answers1

1

Use LineNumberReader on an InputStreamReader. As it is precisely made for that sole purpose.

try (LineNumberReader scInput1 = new LineNumberReader(new InputStreamReader(
        inputStream1, StandardCharsets.UTF_8));
    LineNumberReader scInput2 = new LineNumberReader(new InputStreamReader(
        inputStream2, StandardCharsets.UTF_8))) {

    String line1 = scInput1.readLine();
    String lien2 = scInput2.readLine();
    while (line1 != null && line2 != null) {
        ...
       scInput1.getLineNumber();
       line1 = scInput1.readLine();
       line2 = scInput2.readLine();
    }
}

Here I have added the optional CharSet parameter. A Scanner has additional tokenizing capabilities not needed.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138