settingsAccountsettings
Menusettings

Q: Odd Lines - Java Task (Files and Streams)

+13 votes

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:

Input.txt

Output.txt

Two households, both alike in dignity,
In fair Verona, where we lay our scene,
From ancient grudge break to new mutiny,
Where civil blood makes civil hands unclean.
From forth the fatal loins of these two foes
A pair of star-cross'd lovers take their life;
Whose misadventured piteous overthrows
Do with their death bury their parents' strife.

In fair Verona, where we lay our scene,

Where civil blood makes civil hands unclean.

A pair of star-cross’d lovers take their life;

Do with their death bury their parents’ strife

 

 

 

asked in Java category by user sam

1 Answer

+1 vote
 
Best answer

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

        }
    }
}

 

answered by user samfred5830
selected by user golearnweb
...