4

いくつかのプロパティ ファイルを読み込んで、不足しているキーのテンプレート ファイルと比較しました。

FileInputStream compareFis = new FileInputStream(compareFile);
Properties compareProperties = new Properties();
compareProperties.load(compareFis);

注: テンプレート ファイルも同じように読みます。

読んだ後、それらを比較し、欠落しているキーとテンプレート ファイルの値を Set に書き込みます。

CompareResult result = new CompareResult(Main.resultDir);
[...]
if (!compareProperties.containsKey(key)) {
    retVal = true;
    result.add(compareFile.getName(), key + "=" + entry.getValue());
}

最後に、不足しているキーとその値を新しいファイルに書き込みます。

for (Entry<String, SortedSet<String>> entry : resultSet) {
    PrintWriter out = null;
    try {
        out = new java.io.PrintWriter(resultFile);
        SortedSet<String> values = entry.getValue();
        for (String string : values) {
            out.println(string);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        out.flush();
        out.close();
    }
}

結果ファイルを開くと、テンプレート ファイルの値のすべての改行 "\n" が新しい行に置き換えられていることがわかります。例:

test.key=Hello\nWorld!

になる

test.key=Hello
World!

これは基本的に正しいですが、私の場合は「\ n」を保持する必要があります。

どうすればそれを回避できるか知っている人はいますか?

4

6 に答える 6

2

出力はプロパティ ファイルのように見えるため、Properties.store()を使用して出力ファイルを生成する必要があります。これにより、改行文字だけでなく、他の特殊文字 (非 ISO8859-1 文字など) のエンコードも処理されます。

于 2012-05-07T16:15:26.123 に答える
1

Properties.store()を使用して JB Nizet の回答 (私が思うに最高) に例を追加するには

    FileInputStream compareFis = new FileInputStream(compareFile);
    Properties compareProperties = new Properties();
    compareProperties.load(compareFis);

 ....

    StringBuilder value=new StringBuilder();
    for (Entry<String, SortedSet<String>> entry : resultSet) {

            SortedSet<String> values = entry.getValue();
            for (String string : values) {
                value.append(string).append("\n");
            }
    }
    compareProperties.setProperty("test.key",value);
    FileOutputStream fos = new FileOutputStream(compareFile);
    compareProperties.store(fos,null);
    fos.close();
于 2012-05-07T16:39:27.100 に答える
1

を使用printlnすると、プラットフォーム固有の行終端記号で各行が終了します。代わりに、明示的に必要な行終端記号を書くことができます:

for (Entry<String, SortedSet<String>> entry : resultSet) {
    PrintWriter out = null;
    try {
        out = new java.io.PrintWriter(resultFile);
        SortedSet<String> values = entry.getValue();
        for (String string : values) {
            out.print(string); // NOT out.println(string)
            out.print("\n");
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        out.flush();
        out.close();
    }
}
于 2012-05-07T16:16:24.910 に答える
0

Apache Commons StringEscapeUtils.escapeJava(String)もご覧ください。

于 2012-05-07T16:20:53.353 に答える
0

次のようなものが必要です。

"test.key=Hello\\nWorld!"

"\\n"実際はどこですか\n

于 2012-05-07T16:12:33.333 に答える
0

シリアル化する前に \n をエスケープします。出力ファイルを読み取る場合は、読み取りコードでエスケープを認識する必要があります。

于 2012-05-07T16:13:37.767 に答える