我有一個類,通過讀取上傳的文件,將新的配置添加到現有的配置。問題是它在Windows上運行正常,但在Linux上不是這樣 - 我使用Servlet來接收文件。新配置必須以新行開始,並且不得在任何地方有空行。以下是代碼。爲什麼在附加到文件時,Windows和Linux計算機上的file-io有不同的結果?
public class ConfigGen {
public static void process(File configFile, File uploadedFile)
throws IOException {
synchronized (configFile) {
if (shouldAppend(configFile, uploadedFile)) {
StringBuilder builder = readFile(uploadedFile);
StringBuilder orig = readFile(configFile);
FileWriter writer = new FileWriter(configFile, true);
// If the content ends with a new line character then remove the
// new line from content to be appended
if (orig.toString().endsWith(
System.getProperty("line.separator"))) {
writer.append(builder.substring(1));
} else {
writer.append(builder);
}
writer.flush();
writer.close();
}
}
}
/**
* @param configFile
* @param uploadedFile
* @return true if config change is required, false otherwise
* @throws IOException
*/
private static final boolean shouldAppend(File configFile, File uploadedFile)
throws IOException {
synchronized (configFile) {
String originalConfig = readFile(configFile).toString().trim();
String newAddition = readFile(uploadedFile).toString().trim();
String newSecGroup = newAddition.substring(0,
newAddition.indexOf(":"));
return !originalConfig.contains(newSecGroup);
}
}
private static final StringBuilder readFile(File file) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(file));
String str = "";
StringBuilder builder = new StringBuilder();
while ((str = br.readLine()) != null) {
builder.append(System.getProperty("line.separator") + str);
}
br.close();
return builder;
}
}
附加新配置的文件很多時候會用vim或類似的編輯器手工編輯。我得到的行爲是 - 在Linux機器上。 如果使用vim編輯了該文件,那麼新的文本將追加到新的一行之後,之後的任何後續更新都會顯示在下一行 - 直到使用vim進行編輯。
例如:假設我在文件中有以下內容 - 最初使用vim編寫。
sg-e696a08c:
classes:
tomcat6:
myappmodule:
endpoint: "10.0.2.11"
port: "1443"
,併發布包含以下內容
sg-fde2a89d:
classes:
tomcat7:
servmod:
db: "xyz.com"
port: "1336"
配置文件的預期內容的新文件。
sg-e696a08c:
classes:
tomcat6:
myappmodule:
endpoint: "10.0.2.11"
port: "1443"
sg-fde2a89d:
classes:
tomcat7:
servmod:
db: "xyz.com"
port: "1336"
而是我得到
sg-e696a08c:
classes:
tomcat6:
myappmodule:
endpoint: "10.0.2.11"
port: "1443"
sg-fde2a89d:
classes:
tomcat7:
servmod:
db: "xyz.com"
port: "1336"
通知有一個空行。任何後續發佈的文件都不會導致任何空的新行,直到使用vim編輯文件。我不知道爲什麼我會得到這種行爲。窗戶的結果很好。由於這種行爲,生成的配置變得無效。在Windows上,我使用Notepad ++編輯文件。
難道vim
會在文件末尾添加一些特殊字符,以免丟失或丟失其他內容嗎?我該怎麼做才能解決這個問題,以及爲什麼會這樣做?
這是由於「DOS」和「Unix」約定與「換行符」/「行尾」的含義有所不同。看到這個問題:http://stackoverflow.com/questions/19240082/why-do-gedit-and-vim-hide-the-final-newline-from-the-user – pandubear
嘗試刪除條件'(orig.toString ().endsWith()',並使用'writer.append(builder.trim());' – iTech
使用'writer.append(builder.trim());'在使用vim進行編輯之後首次上傳是正確的,但否則在下次上傳時,文本從第一次上傳後的同一行開始。 – ykesh