Mor Eru
Mor Eru

Reputation: 1129

How to make Java ignore escape sequences in a String?

I am writing a Java code to read Blob objects from an Oracle database table.

I need to retrieve the blob objects and store them into a String for further processing. I convert the blob objects contents to String by this :

java.sql.Blob blob = rs.getBlob(i);
columnValue = new String(blob.getBytes(1l, (int) blob.length()));

However when I try to parse the resultant string, I get errors which say "Not a valid escape sequence" because apparently the Blob data consists of some data like \x, \i or something !

Is there a way to make Java ignore these escape sequences and make it to just consider the string with its contents as it is (i.e Strings containing \x, \i etc.) ?

Upvotes: 1

Views: 8069

Answers (2)

user166390
user166390

Reputation:

The problem has nothing to do with "\x" escape sequences. (These escape sequences only have meaning in string literals -- they have nothing to do with new String. The escape sequences found in regular expressions are just an interpretation of a string.)

The problem is that the blob contains data which is invalid for the given encoding. From the new String(byte[]) documentation:

The behavior of this constructor when the given bytes are not valid in the default charset is unspecified. The CharsetDecoder class should be used when more control over the decoding process is required.

Also do note that new String(byte[]) should not be used because (also from the documentation):

Constructs a new String by decoding the specified array of bytes using the platform's default charset.

I suspect thus that either

  1. The blob data used is outright invalid and/or;
  2. The "default charset" does not match the encoding of the supplied bytes

Happy coding

Upvotes: 2

Bozho
Bozho

Reputation: 597106

I assume that by "parse" you mean something related to regex, because otherwise storing these values in a string will work fine - the escape sequences are useful only for string literals and regexes.

Anyway, StringEscapeUtils.escapeJava(..) should do what you want (it's from commons-lang)

Apart from that - you should use java.sql.Clob for textual data.

Upvotes: 3

Related Questions