我試圖從現有文件的每行第100個字符處引入一個換行符,但它不會寫入任何內容。下面是用java編寫的代碼,用於讀取現有文件並用臨時文件寫入它。從Java讀取並編輯文件
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class ReplaceFileContents {
public static void main(String[] args) {
new ReplaceFileContents().replace();
}
public void replace() {
String oldFileName = "Changed1.ldif";
String tmpFileName = "Changed2.ldif";
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
while ((line = br.readLine()) != null) {
line.replaceAll("(.{100})", "$1\n");
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
// Once everything is complete, delete old file..
File oldFile = new File(oldFileName);
oldFile.delete();
// And rename tmp file's name to old file name
File newFile = new File(tmpFileName);
newFile.renameTo(oldFile);
}
}
請勿沉默'例外'!嘗試在控制檯上輸出它們。 – ortis
你不是寫信給'bw'的任何地方 –
而不是逐行讀取和處理文件,爲什麼不一次只讀一個字節,同時跟蹤消耗的字節數,一旦計數達到100就追加一個新行。 –