gpt4 book ai didi

java - 从文本文件中删除多余的空格

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

我有以下格式的文本文件数:

196903274115371008    @266093898 

Prince George takes his first public steps with his mom, Catherine, Duchess of

Cambridge.

我想删除除第一个换行符之外的所有额外空格 + 换行符。所以我想上面是这样的:
196903274115371008@266093898 

Prince George takes his first public steps with his mom, Catherine, Duchess of Cambridge.

我写了以下代码:
package remove_white_space222;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


public class Remove_white_space222 {

public static void main(String[] args) throws FileNotFoundException, IOException {

FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("outfile.txt");
String line;

while((line = br.readLine()) != null)
{
line = line.trim(); // remove leading and trailing whitespace
line=line.replaceAll("\\s+", " ");
fw.write(line);


}
fr.close();
fw.close();
}

}

在此先感谢您的帮助,,,,

最佳答案

    File file = new File("input_file.txt");
try(BufferedReader br = new BufferedReader(new FileReader(file));
FileWriter fw = new FileWriter("empty_file.txt")) {
String st;
while((st = br.readLine()) != null){
fw.write(st.replaceAll("\\s+", " ").trim().concat("\n"));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

关于java - 从文本文件中删除多余的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24256195/

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