简体   繁体   中英

Get every n-th line from text-file, reverse it and print out

I writing function which get: file-path and number as parameters. Function open this file and get every n-th line from it, reverse it and print out to console.

Until now i manage to do something like:

public static void reverseText(String filePath, int colle) // int colle = n-th line
{
    BufferedReader fileRead = null;

    String line;        

    try
    {
        File file = new File(filePath);
        if (!(file.exists()))
            file.createNewFile();

        fileRead = new BufferedReader(new FileReader(file));

        while ((line = fileRead.readLine()) != null)
        { 

        }


        fileRead.close();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}

What I mean is that in file for example are following lines of text (int colle = 2, so we get every 2nd line form file)

first line second line <-- this
third line fourth line <-- and this

(read file and reverse get lines) --> Output print out in console:

"enil dnoces" "enil htruof"

I guess for reverse I should use StringBuilder but first i need get these lines and I have no idea how to read every n-th line...

Thanks for any help!

Solution below read all lines and then select every n-line, reverse and print.

public static void main(String[] args) throws IOException {
    int frequency = 5;
    final List<String> strings = Files.readAllLines(Paths.get("/home/test.txt"));
    List<String> collect = IntStream.range(0, strings.size())
            .filter(c -> c % frequency == 0)
            .mapToObj(c -> strings.get(c))
            .collect(Collectors.toList());

    collect.forEach(str ->
            System.out.println(new StringBuilder(str).reverse())
    );
}

IntStream is necessary to get specific lines from collection strings. Then one by one lines are reversed and printed. It can be one liner but decided to make it more readable.

Use line counter to control loop iterations:

int n = 3;
StringBuilder sb = new StringBuilder();
for (int i = 0; (line = fileRead.readLine()) != null; i++) {
     if (i % n == 0) {
        sb.delete(0, line.length())
        System.out.println(sb.append(line).reverse());
     }
}

You still can do it using while defining a variable for that.

Thanks everybody for help. Below i posted working code for my expectations

public static void reverseText(String filePath, int colle)
{   
    BufferedReader fileRead = null;
    StringBuilder builder = new StringBuilder();
    int lineCounter = 0;
    String line;      

    try
    {
        File file = new File(filePath);
        if (!(file.exists()))
                file.createNewFile();

        fileRead = new BufferedReader(new FileReader(file));

        while ((line = fileRead.readLine()) != null)
        { 
            lineCounter++;
            if (lineCounter %colle == 0)
            {
                builder.delete(0, line.length());
                System.out.println(builder.append(line).reverse());
            } 
        }

        fileRead.close();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
 }

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