I have hit the wall!
After reading alot of interesting threads on StackOverflow, I have tried a lot of different solutions, but nothing seems to work.
Let's assume I have a .txt-file where I want to replace line breaks with "XXX". I use a count-method to count the lines in the document.
Scanner reader = new Scanner("document.txt);
String [] textToArray = new String[count];
for(int i = 0; textToArray.length; i++){
String text = reader.nextLine();
text = text.replaceAll("\n", "XXX");
textToArray[i] = text;
}
I then use a for each loop to print out the text. The output is still the same as the original.
I have also tried "\n", "\r", "\r" even "\r\n".
Read the documentation, i.e. the javadoc of nextLine()
:
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
So, you're reading the text of each line, but you will not see the \r
and/or \n
characters.
Since you're reading each line into an array, you should just append XXX
to each value:
for (int i = 0; textToArray.length; i++) {
String text = reader.nextLine();
textToArray[i] = text + "XXX";
}
Unrelated
I would also suggest that you read into a List
, instead of an array. You can always convert to array afterwards.
And I hope you remember to close the Scanner
, and that you showed mock code, because new Scanner("document.txt")
will scan the text document.txt
, not the content of a file by that name.
String[] textToArray;
try (Scanner reader = new Scanner(new File("document.txt"))) {
List<String> textList = new ArrayList<>();
for (String text; (text = reader.nextLine()) != null; ) {
textList.add(text + "XXX");
}
textToArray = textList.toArray(new String[textList.size()]);
}