简体   繁体   中英

How to read every second line from a file in java

Can someone tell me how to read every second line from a file in java?

  BufferedReader br = new BufferedReader(new FileReader(file));
    String line = br.readLine();
        while(line != null){

            //Do something ..

           line = br.readLine()
        }

   br.close

One simple way would be to just maintain a counter of number of lines read:

int count = 0;
String line;
while ((line = br.readLine()) != null) {
    if (count % 2 == 0) {
        // do something with this line
    }
    ++count;
}

But this still technically reads every line in the file, only choosing to process every other line. If you really only want to read every second line, then something like RandomAccessFile might be necessary.

You can do it in Java 8 fashion with very few lines :

static final int FIRST_LINE = 1;
Stream<String> lines = Files.lines(path);
String secondLine = lines.limit(2).skip(FIST_LINE).collect(Collectors.joining("\n"));
  1. First you stream your file lines
  2. You keep only the two first lines
  3. Skip the first line

Note : In java 8, when using Files.lines(), you are supposed to close the stream afterwards or use it in a try-with-resource block.

This is similar to @Tim Biegeleisen's approach, but I thought I would show an alternative to get every other line using a boolean instead of a counter:

boolean skipOddLine = true;
String line;
while ((line = br.readLine()) != null) {
    if (skipOddLine = !skipOddLine) {
        //Use the String line here
    }
}

This will toggle the boolean value every loop iteration, skipping every odd line. If you want to skip every even line instead you just need to change the initial condition to boolean skipOddLine = false; .

Note: This approach only works if you do not need to extend functionality to skip every 3rd line for example, where an approach like Tim's would be easier to modify. It also has the downside of being harder to read than the modulo approach.

This will help you to do it very well

  • You can use try with resource
  • You can use stream api java 8
  • You can use stream api supplier to use stream object again and again
  • I already hane added comment area to understand you
try (BufferedReader reader =
                    new BufferedReader(
                        new InputStreamReader(
                            new ByteArrayInputStream(x.getBytes()),
                            "UTF-8"))) { //this will help to you for   various languages  reading files

Supplier<Stream<String>> fileContentStream = reader::lines; // this will help you  to use stream object again and again

                  if (FilenameUtils.getExtension(x.getOriginalFilename()).equals("txt")) { this will help you to various files extension filter

                  String secondLine = lines.limit(2).skip(FIST_LINE).collect(Collectors.joining("\n")); 


                    String secondLine =
                        fileContentStream
                            .get()
                            .limit(2)
                            .skip(1)// you can skip any line with this action
                            .collect(Collectors.joining("\n"));

                            }
                            else if (FilenameUtils.getExtension(x.getOriginalFilename()).equals("pdf")) {


 } catch (Exception ex) {

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM