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

Jam*_*mes 1 java text readline

我有以下文本文件。我一次阅读每一行,并将整行推入一个字符串。目前,我的代码仅逐行读取而无需担心任何空格,因此

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

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

Textfile.txt

Text random text random numbers etc. This is a random
text file.
Run Code Online (Sandbox Code Playgroud)

Keq*_* Li 5

读完这些行后,字符串中没有任何'\ n'字符。因此,您需要做的是按空间连接这些行。只需使用String.join()

在Java 8中,您需要做的是:

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

更新

正如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();
Run Code Online (Sandbox Code Playgroud)