Reversing a properties file content

279 Views Asked by At

I've a properties file (say exmp.properties) which is something like this

1. k5=500
2. k4=400
3. k3=300
4. k2=200
5. k1=100

I need to reverse the content of this file like

1. k1=100
2. k2=200
3. k3=300
4. k4=400
5. k5=500

Is there any way I can achieve this using ANT task or Java code?

3

There are 3 best solutions below

0
On BEST ANSWER

Here's a solution with loadresource and nested filterchain.
To make it work correctly your propertyfile needs a linefeed after last property, means :

k5=500
k4=400
k3=300
k2=200
k1=100
-- empty line --

snippet :

<project>
 <loadfile property="unsorted" srcfile="foobar.properties"/>
 <echo>unsorted: ${line.separator}${unsorted}</echo>

 <loadresource property="sorted">
  <string value="${unsorted}" />
   <filterchain>
    <sortfilter />
   </filterchain>
 </loadresource>
 <echo>sorted: ${line.separator}${sorted}</echo>
 <!-- write file -->
 <echo file="foobar_sorted.properties">${sorted}</echo>
</project>

output :

[echo] unsorted:
[echo] k5=500   
[echo] k4=400   
[echo] k3=300   
[echo] k2=200   
[echo] k1=100   
[echo] sorted:  
[echo] k1=100   
[echo] k2=200   
[echo] k3=300   
[echo] k4=400   
[echo] k5=500
0
On
0
On

You need to do something like this:

String input = "in.txt";
String output = "out.txt";

try (FileWriter fw = new FileWriter(output)) {
    //read all lines
    List<String> lines = Files.readAllLines(Paths.get(input), Charset.defaultCharset());

    //clear contents of the output file
    fw.write("");
    //write all lines in reverse order
    for (int i = lines.size() - 1; i >= 0; i--) {
        fw.append(lines.get(i) + System.lineSeparator());
    }
} catch (Exception e) {}    

This reads all lines of the file and then writes them in reverse order.