I had an issue with my code because my file path somehow ended up with a "\\n" at the end of the path which caused issues when trying to use the file, as it would not be able to find that file.
For debugging purposes, how can I print out a string INCLUDING things like \\b
\\n
\\r
etc.?
Eg
System.out.println(file.getAbsolutePath).withSpecials()
which will print to console:
C:/folder/filename.extension\n
You could try using this code, which escapes a string. This takes care of all escapes except \\u\u003c/code> , which should display fine anyway.
public static String escape(String str) {
str = str.replace("\b", "\\b");
str = str.replace("\t", "\\t");
str = str.replace("\n", "\\n");
str = str.replace("\r", "\\r");
str = str.replace("\f", "\\f");
str = str.replace("\'", "\\'");
str = str.replace("\\", "\\\\");
return str;
}
This function can be used as follows:
System.out.println(escape("123\n\rabc"));
public class Main {
public static void main(String arg[]) {
String str = "bla\r\n";
System.out.print(str); // prints "bla" and breaks line
System.out.print(Main.withEndings(str)); // prints "bla\r\n"
// Breaks a line
System.out.println();
// Every char is a number, Java uses by default UTF-16 char encoding
char end = '\n';
System.out.println("Char code: " + (int)end); // prints "Char code: 10"
}
public static String withEndings(String str) {
// Replace the character '\n' to a string with 2 characters the '\' and the 'n',
// the same to '\r'.
return str.replace("\n", "\\n").replace("\r", "\\r");
}
}
You can print the \\n
by doing string.replace("\\n", "\\\\\\\\n");
So to print it out do: System.out.println(file.getAbsolutePath().replace("\\n", "\\\\\\\\n"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.