我想通過Java編輯現有的文件,在行的每個第4個字符後面都有一個換行符,後跟一個空格。所以下面是期望值。Java編輯現有文件
File Content
------------
abcdef
gh
ijklmn
Expected output
--------------
abcd
ef
gh
ijkl
mn
下面是已嘗試的代碼,但是這將全部寫入一行。
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=line.replaceAll("(.{4})", "$1\n ");
bw.write(line);
}
} 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);
}
您對此代碼有什麼問題? – Sanjeev
@Sanjeev根據問題''但這寫在一個單一的所有行'# –
如果您使用'「$ 1」+ System.getProperty(「line.separator」);'而不是'「$ 1 \ n」? – npinti