问题描述
我在Postgresql数据库中存储了一个bytea列。
I have a bytea column stored in Postgresql db.
ColumnName:test
ColumnName:test
Ex: \x61736461640061736461736400
当我在选择查询中使用encode(test,'escape')时,会得到类似的内容。
When I use encode(test,'escape') in my select query i get something like this.
Ex: asdad\000asdasd\000
但是如果要用Java进行编码转义,该怎么做?
,即如果我有
But How to do it If want to do encode-escape in Java? i.e If i have
String str = \x61736461640061736461736400
如何获取 asdad\000asdasd\000
作为字符串数组?
how to get asdad\000asdasd\000
as array of strings ?
谢谢。
推荐答案
您想要一个字符串数组还是想要 asdad\000asdasd\000
?您是在使用字节数组还是实际的字符串?
Do you want an array of strings or do you want asdad\000asdasd\000
? Are you working with a byte array or an actual String?
字符串到字节数组(如果使用字符串)
String str = "\x61736461640061736461736400"
str = str.substring(2); //get rid of \x
byte [] bytes = new byte[str.length()/2];
for(int i = 0; i < result.length; i++) {
String numberStr = str.substring(i*2,i*2+2);
int numberInt = Integer.parseInt(numberStr);
bytes[i] = (byte) numberInt;
}
字节数组到字符串ArrayList
ArrayList<String> result = new ArrayList<String>();
int startIndex = 0;
for(int i = 0; i < bytes.length; i++) {
if(bytes[i] == 0) {
if(startIndex > i) {
byte [] stringBytes = new byte[i - startIndex];
for(int j = startIndex; j < i; j++) {
stringBytes[j-startIndex] = bytes[j];
}
result.add(new String(stringBytes, "US-ASCII"));
}
startIndex = i+1;
}
}
字节数组为八进制转义字符串
DecimalFormat formatter = new DecimalFormat("000");
StringBuilder resultBuilder = new StringBuilder();
for(byte b : bytes) {
if(b > 0) {
char c = (char) b;
resultBuilder.append(c);
} else {
int bInt = b & 0xFF;
String octal = Integer.toString(bInt, 8);
int numPadZeroesNeeded = 3 - octal.length();
resultBuilder.append('\');
for(int i = 0; i < numPadZeroesNeeded; i++) {
resultBuilder.append('0');
}
resultBuilder.append(octal);
}
}
这篇关于什么是java中的encode(< columnName> ;,'escape')PostgreSQL等效项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!