我有一個屬性文件(說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代碼實現這一點?
我有一個屬性文件(說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代碼實現這一點?
以下是loadresource和嵌套filterchain的解決方案。
要使它正常工作,你propertyfile最後一個屬性之後需要一個換行符,意思是:
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
從爲什麼你想要的答案
那只是一個文本文件。 「Read in the file line by line」「reverse it」和「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) {}
這讀取文件中的所有行,然後以相反的順序將它們寫入。
除了扭轉屬性文件的內容?因爲您可以在訂單無關緊要的情況下獲取所需的任何財產? – Nakul91
爲什麼?訂單在屬性文件中不重要。這是一個哈希映射。按文件順序沒有順序訪問。 – EJP
聽起來像一個家庭作業練習給我。 –