私は現在、INI ファイル解析ライブラリに取り組んでいますが、作成したメソッドでカテゴリを作成しようとすると、1 つだけ問題が発生します。
私が使用している INI ファイルの内容は次のとおりです。
; Format example
[Category]
key=value
; Just a test to see if setting the same key in a different category
; would mess up the reading, which it didn't.
[Language]
cplusplus=C++
key=java
(No extra line; file ends at "key=java")
メソッドを使用してカテゴリを作成すると、十分な数の新しい行を追加しようとするため、各カテゴリには前のカテゴリの終わりと作成中のカテゴリの間に空白行が 1 行あります。ファイルの最後に余分な空白行がないままファイルを保持すると、正常に動作します。しかし、ファイルの内容を次のように変更すると:
; Format example
[Category]
key=value
; Just a test to see if setting the same key in a different category
; would mess up the reading, which it didn't.
[Language]
cplusplus=C++
key=java
(File has extra line; file ends after the "key=java" line)
2 つのカテゴリの間に 2 つの空の行が作成されます...しかし、最後の行が既に空白であるかどうかを確認すると、その理由がわかりません。私は Java に少し慣れていないので、明らかな間違いを犯している場合は教えてください。
/**
* Adds a category to the current INI file.
*
* @param category The category to be added to the file
*/
public void addCategory(String category) {
if (iniFile == null) return;
// Checking to see if the file already contains the desired category
boolean containsCategory = false;
String lastLine = "";
String string;
try (BufferedReader in = new BufferedReader(new FileReader(iniFile))) {
while ( (string = in.readLine()) != null) {
// Line is a comment or is empty, ignoring
if (!string.equals(""))
if (string.charAt(0) == ';' || string.charAt(0) == '#')
continue;
lastLine = string;
// Line is a category, checking if it is the category that is
// about to be created
if (!string.equals("") && string.charAt(0) == '[') {
String thisCategory = string.substring(1, string.length() - 1);
if (thisCategory.equals(category))
containsCategory = true;
}
}
} catch (IOException e) {}
// The file does not contain the category, so appeanding it to the end
// of the file.
if (!containsCategory) {
try (BufferedWriter out = new BufferedWriter(new FileWriter(iniFile, true))) {
if (!lastLine.equals("")) {
System.out.println("Adding extra whitespace");
out.newLine();
out.newLine();
}
out.write('[' + category + ']');
out.close();
} catch (IOException e) {}
}
}
完全なファイル ソースを表示する場合は、アップロード先のGitHubへのリンクを次に示します。
編集:
addCategory(String)
メソッドを呼び出した後、ファイルがどのように見えるかを提供する必要があると思いました。
最初のファイルを呼び出しaddCategory("Example")
た後 (余分な空白行はありません):
; Format example
[Category]
key=value
; Just a test to see if setting the same key in a different category
; would mess up the reading, which it didn't.
[Language]
cplusplus=C++
key=java
[Example]
2 番目のファイルを呼び出しaddCategory("Example")
た後 (ファイルの最後に余分な空白行を追加):
; Format example
[Category]
key=value
; Just a test to see if setting the same key in a different category
; would mess up the reading, which it didn't.
[Language]
cplusplus=C++
key=java
[Example]