Reputation: 57
for a Java project for a University Class I have a method that saves ASCII images as a uniline string and another method called toString rebuilds this ASCII image and returns as a string. When I run my program on the Eclipse my output looks on console alright and multiline, and there are line breaks where they should be. But when I run it with the command line with a redirected outputfile
java myprogram < input > output
the text in the output is uniline without line breaks
Here is the code of the method
public String toString(){
String output = "";
for(int i=0; i<height; i++){
output=output+image.substring(i*width, i*width+width)+"\n";
}
return output;
}
What should I do so I can get a multiline output text file
Upvotes: 0
Views: 1203
Reputation: 109613
A faster solution with \r\n when Windows:
public String toString() {
final String EOL = System.getProperty("line.separator");
final int EOL_LENGTH = EOL.length();
StringBuilder output = new StringBuilder(image.length() + EOL_LENGTH * height);
output.append(image);
for (int i = 0; i < height; i++) {
output.insert(i*(width + EOL_LENGTH) + width, EOL);
}
return output.toString();
}
Upvotes: 0
Reputation: 735
It may be the case that \n
isn't the correct line separator for the operating system you are running. With Java, it's best to use System.getProperty("line.separator");
for creating newline characters, as this will ensure you are using the correct one for the platform.
Upvotes: 3