反转属性文件内容

Reversing a properties file content

我有一个属性文件(比如说 exmp.properties),它是这样的

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

我需要像这样反转这个文件的内容

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

有什么方法可以使用 ANT 任务或 Java 代码来实现吗?

那只是一个文本文件。 “Read in the file line by line" "reverse it" and "write to the file again”。

你需要做这样的事情:

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) {}    

这会读取文件的所有行,然后以相反的顺序写入它们。

这是 loadresource and nested filterchain 的解决方案。
为了使其正常工作,您的 属性 文件需要在最后一个 属性 之后换行,意思是:

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

片段:

<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>

输出:

[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