gpt4 book ai didi

Java读取多行文本文件,在最后一个字符后的每行末尾添加分隔符

转载 作者:行者123 更新时间:2023-11-29 07:35:03 24 4
gpt4 key购买 nike

我有以下文本文件。我一次读取每一行并将整行插入一个字符串。目前,我的代码只是逐行读取而不关心任何空格,所以

random text 变为 randomtext。有没有办法在该行的最后一个字符后插入一个空格?我已经尝试了以下代码,但它没有完成这项工作。

d = d.replaceAll("\n", "");

文本文件.txt

Text random text random numbers etc. This is a random
text file.

最佳答案

在你读入这些行之后,你的字符串中没有任何 '\n' 字符。所以,你需要做的是用空格连接这些线。只需使用 String.join()

在 Java 8 中,您只需要:

File f = new File("your file path");
List<String> lines = Files.readAllLines(file.toPath());
String result = String.join(" ", lines);

更新

正如 Shire 在下面的评论中指出的那样,如果文件很大,最好使用缓冲读取器读取每一行并用空格将它们连接起来。

这里是如何使用BufferredReader

File file = new File("file_path");
StringBuilder sb = new StringBuilder();

try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;

while ((line = reader.readLine()) != null) {
sb.append(line).append(" ");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
String result = sb.toString();

关于Java读取多行文本文件,在最后一个字符后的每行末尾添加分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36922206/

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