[Solved] Odd Lines - Java Task (Files and Streams)

  

3
Topic starter

Write a program that reads a text file and writes its every odd line in another file.

Line numbers starts from 0.

Read 01_OddLinesIn.txt and test your output against 01_OddLinesOut.txt, then read 02_OddLinesIn.txt and test against its respective output file and so on.

Examples:

odd lines java
1 Answer
2

Here is the solution:

import java.io.*;
 
public class Pr_01_OddLines {
    public static void main(String[] args) throws IOException {
        File fileIn1 = new File("resources\\01_OddLinesIn.txt");
 
        try (BufferedReader bf = new BufferedReader(new FileReader(fileIn1))) {//SURROUND WITH try with resources FOR THE EXCEPTIONS
 
            String readLine;
            int line = 0;
 
            while ((readLine = bf.readLine()) != null) {
                if (line % 2 != 0) {//CHECKING WHETHER THE ROW IS ODD
                    System.out.println(readLine);
                }
                line++;
            }
         }
    }
}
Share: