Possible Duplicate:
How do I print escape characters in Java
I am writing a program which reads a String from a file and generates tokens from that file.
Eg. if the file is '1\t .\n$$$'
then the java String I want is exactly same. So String str should look like '1\t .\n$$$'
The problem is that as soon as I encounter a '\' (backslash) which can represent a \t or a \n, then the next character (t or n) gets lost.
I am using bufferedreader class and reading the file character by character by using the function read. Here is the piece of code.
Charset encoding = Charset.defaultCharset();
InputStream in = new FileInputStream(new File (filepath));
Reader reader = new InputStreamReader(in, encoding);
// buffer for efficiency
buffer = new BufferedReader(reader);
String temp = "";
while ((r = buffer.read()) != -1) {
ch = (char) r;
if (ch != '\\') {
temp += ch;
} else if (ch == '\\'){
ch = (char) buffer.read();
if (ch == 'n') {
temp += "\\n";
} else {
temp += "\\t";
}
}
}
I have also tried using the UTF-8 charset for encoding
(Charset encoding = Charset.forName("UTF-8");)
but that does not help.
Thanks in advance.