Reputation: 95
When looping through a text file with each item on a different line, the loop keeps getting an extra white space as one of the values.
try {
BufferedReader br = new BufferedReader(new FileReader("Words.txt"));
String line;
while ((line = br.readLine()) != null) {
event.getTextChannel().sendMessage(line + "; ").queue();
}
br.close();
}
The result I'm getting is:
廊下;
;
火星;
;
意味;
;
but I want 廊下; 火星; 意味;
Upvotes: 0
Views: 63
Reputation: 95
I have fixed it by adding if (!line.equals("")) before the line that prints the text.
Upvotes: 0
Reputation: 615
There could be a cleaner way of doing it depending on your actual way of sending the message as pointed out in the comments. You could however try doing something like this:
try {
BufferedReader br = new BufferedReader(new FileReader("Words.txt"));
StringBuilder builder = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
builder.append(line.replace("\n", "").replace("\r", "")).append("; ")
}
br.close();
event.getTextChannel().sendMessage(builder.toString()).queue();
}
EDIT: You really should try to find out where the extra empty lines come from, but a temporary workaround would be to skip over empty lines:
try {
BufferedReader br = new BufferedReader(new FileReader("Words.txt"));
StringBuilder builder = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
String stripped = line.replace("\n", "").replace("\r", "");
if (!stripped.isEmpty()) {
builder.append(stripped).append("; ")
}
}
br.close();
event.getTextChannel().sendMessage(builder.toString()).queue();
}
Upvotes: 2