James
James

Reputation: 31

Java reading multi line text file, add delimiter at the end of each line after final character

I have the following text file. I am reading each line at a time and pushing the whole line into a String. Currently, my code just reads each line by line without concern for any spaces so

random text becomes randomtext. Is there a way to insert a space after the last character in the line? I have tried the following code and it does not do the job.

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

Textfile.txt

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

Upvotes: 1

Views: 2592

Answers (2)

Harish
Harish

Reputation: 726

Obviously there are better ways, like the first answer. I suggest another way using Java 8. This may not be a perfect solution - just another way to solve a problem. I use similar blocks as below:

InputStream is = this.getClass().getResourceAsStream(filename);

Then, build a StringBuilder to extract the file contents as a full string including lines.

final StringBuilderWriter writer = new StringBuilderWriter();
    try {
        IOUtils.copy(is, writer, StandardCharsets.UTF_8);
    } catch (IOException e) {
        writer.append("exception", e));
    }
    return writer.toString();

And then, apply .split(\n) on the returned string above.

Further more, to iterate each line from the split string:

Arrays.asList(string).split("\n"))

Upvotes: 0

lkq
lkq

Reputation: 2366

After you read the lines in, there isn't any '\n' character in your string. So, what you need to do is to join these lines by space. Just use String.join()

In Java 8, all you need is:

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

UPDATE

As Shire pointed out in the comment below, if the file is of huge size, it's better to use a buffered reader to read each line in and concatenate them with a space.

Here is how to use a 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();

Upvotes: 5

Related Questions