gpt4 book ai didi

Java编辑现有文件

转载 作者:行者123 更新时间:2023-12-01 09:59:40 25 4
gpt4 key购买 nike

我想通过 Java 编辑现有文件,以在该行的每个 4 个字符后添加一个换行符和一个空格。因此,以下是期望。

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);

}

最佳答案

您的代码没有在每行后面写入行分隔符。需要专门添加

     while ((line = br.readLine()) != null) {       
line=line.replaceAll("(.{4})", "$1\n ");
bw.write(line);
bw.newLine();
}

关于Java编辑现有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36906179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com