gpt4 book ai didi

java - 格式化 .txt 文件中的文本

转载 作者:行者123 更新时间:2023-11-30 11:33:58 28 4
gpt4 key购买 nike

我必须为这样的文本文件创建一个小程序:

hello_this_is_a_test_Example_
this line has to go up because it has a space at the beginning
this one too
this is the next line because there's no space at the start
this one has to connect with the first line

希望你明白。

所以最后,它应该将格式化的文本保存在这样的文件中:

hello_this_is_a_test_Example_ this line has to go up because it has a space at the beginning this one too
this is the next line because there's no space at the start this one has to connect with te upper again

基本上,如果该行在每个字符串的开头都有一个空格字符,则它必须与顶行相连。我已经有了 GUI 来选择两个文件,只需要算法。提前谢谢你:D

我现在有这个,但它把所有内容都放在一行中。这是不对的:

public class Engine {

public void Process(String fileIn,String fileOut) throws IOException{
System.out.println("[Info]--> Processign");
System.out.println("[Info]--> FileIn = " + fileIn);
System.out.println("[Info]--> FileOut = " + fileOut);
FileWriter Writer = new FileWriter(fileOut);

BufferedReader br = new BufferedReader(new FileReader(fileIn));
String line;
String modified;
while ((line = br.readLine()) != null) {
System.out.println(line);
Writer.write(line);
if(line.startsWith(" ")){
modified = line.replaceAll("\n ", " ");
Writer.write(modified);
}
}
br.close();
Writer.close();}
}

最佳答案

试试这个:

String modified = yourString.replaceAll("\n ", " ");

尝试这样的事情:

StringBuilder builder = new StringBuilder();
foreach (string line in Files.ReadAllLines(@"c:\myfile.txt"))
{
builder.append(line);
}
String modified = builder.toString().replaceAll("\n ", " ");
FileWriter fw = new FileWriter(@"c:\myfile.txt");
fw.write(modified);
fw.close();

关于java - 格式化 .txt 文件中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15900553/

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