I'm trying to printf a String where field width is given by a variable, rather than hard coded in the format string. Plus, I want printf to start the string on a new line.
System.out.printf("\r\n>%-32s<", "Hello World"); //works ok
output (the initial newline doesn't show up in the stackoverflow formatter):
>Hello World <
The cheverons here are not command line prompts, but are to visually confirm the width of the field.
However, if I try constructing the format string dynamically, using as far as I can see the correct escape sequences, I can't get the initial return & new line characters to actually cause a return & new line.
import java.util.*;
class DynamicFormatStringTest {
private static final int TEXT_LENGTH = 32;
public static void main(String[] args){
String myFormat = "\\r\\n>%-" + TEXT_LENGTH+ "s<";
//System.out.println(myFormat); //prints \r\n>%-32s<
System.out.printf(myFormat, "Hello World");
}
}
output:
\r\n>Hello World <
I'm getting the literal \r\n output.
Could anyone tell me what the correct technique is?