【发布时间】:2009-10-21 10:46:32
【问题描述】:
想要截断错误字符串,以确保它适合 Oracle 表列 VARCHAR2(2000 BYTE)
设计力量:
主要目标是适合表格列。
90-95% 的字符串文本是异常消息和堆栈跟踪。但它可能包含一些带有法语、土耳其语字符的客户名称,我愿意忽略这些字符并将其视为?或其他。
我希望代码非常简单。数据库编码可以改变。可以引入汉字,但我还是想让代码工作。
应该是“非常简单”,但它让我思考了一段时间。
什么是建议?
可能最好的选择是转换为 ascii。但我想出了一个不好但可能有效的变体。
public static String trimStringToBytes(StringBuilder builder, int maximumBytes)
{
String truncatedString = builder.length() > maximumBytes ? builder.substring(0, maximumBytes) : builder.toString();
byte[] bytes;
String asciiCharsetName = "US-ASCII";
try
{
bytes = truncatedString.getBytes(asciiCharsetName);
}
catch (UnsupportedEncodingException e)
{
//not really possible as JVM should support always US-ASCII but anyway
int worstCaseScenarioBytesPerCharacter = 4;
bytes = truncatedString.substring(0, truncatedString.length() / worstCaseScenarioBytesPerCharacter).getBytes();
}
return new String(bytes, 0, bytes.length > maximumBytes ? maximumBytes : bytes.length);
}
【问题讨论】:
标签: java oracle character-encoding