Posts

Showing posts with the label 字符串截断

A New Collection of Thoughtful Learning Apps — Now Available on iOS & Android

Image
I’m excited to share a set of mobile apps I’ve recently completed and published on both the Google Play Store and the Apple App Store. These apps are designed with a simple goal in mind: to make meaningful, structured content more accessible, whether you’re studying theology or improving your English vocabulary. 📱 Now Available on Both Platforms All apps are live and available for download: Google Play Developer Page: https://play.google.com/store/apps/dev?id=5835943159853189043 Apple App Store Developer Page: https://apps.apple.com/ca/developer/q-z-l-corp/id1888794100 📖 Theology & Confession Study Apps For those interested in Reformed theology and classical Christian teachings, I’ve developed a series of apps that present foundational texts in a clean, focused reading format: The Belgic Confession Canons of Dort Heidelberg Catechism Westminster Shorter Catechism Each app is designed to provide a distraction-free experience, making it easier to read, reflect, and revisit these im...

Java如何安全按字节长度截断String(UTF-8完整解决方案)

Image
Java如何安全按字节长度截断String(UTF-8完整解决方案) 在Java开发中,我们经常需要对字符串进行长度限制,比如: 数据库字段有字节长度限制 接口参数有大小限制 日志或消息需要截断 很多人第一反应是使用: value.substring(0, n) 但这种方式在涉及 UTF-8 编码 时是 不安全的 。 问题本质:字符长度 ≠ 字节长度 在 UTF-8 编码中: 英文字符 → 1 byte 中文字符 → 3 bytes Emoji → 4 bytes 例如: "hello" → 5 bytes "你好" → 6 bytes "😊" → 4 bytes 因此: substring 按字符截断,无法控制字节大小 --- Java 标准库有没有现成方法? 答案是: 没有直接可用的方法 。 虽然 Java 提供了: CharsetEncoder ByteBuffer String.getBytes() 但都需要手动处理,且实现复杂,不适合直接使用。 --- 错误实现方式(常见坑) ❌ 方式1:substring value.substring(0, 50); 问题:可能超过字节限制 ❌ 方式2:直接截断 byte[] new String(bytes, 0, maxBytes, UTF_8); 问题: 可能截断多字节字符 产生乱码(�) --- 正确实现:UTF-8安全按字节截断 public static String truncateUtf8(String value, int maxBytes) { if (value == null) return null; byte[] bytes = value.getBytes(StandardCharsets.UTF_8); if (bytes.length <= maxBytes) return value; int len = maxBytes; // 找到字符起点 int star...

解决数据库“value too long for column”错误:Java中基于字节的UTF-8字符串截断

Image
解决数据库“value too long for column”错误:Java中基于字节的UTF-8字符串截断 如果你在 Java 后端开发中遇到过 “value too long for column” 的数据库错误,那么问题的根本原因可能并不像表面看起来那么简单。 本文将通过一个真实的生产事故,讲清楚 UTF-8 编码 带来的坑,以及为什么 字符串长度不等于字节长度 ,并提供一个 安全按字节截断字符串 的正确实现方式。 生产问题复盘 我们在生产环境遇到如下错误: value too long for column 数据库字段限制: 50 bytes 输入字符串长度: 53 个字符 代码已做处理:截断为 50 个字符 看起来完全没问题,但插入数据库时依然失败。 根本原因:UTF-8 编码 字符数 ≠ 字节数 在 UTF-8 编码中: 英文字符(ASCII)→ 1 字节 中文字符 → 通常 3 字节 Emoji → 4 字节 因此,一个 50 个字符的字符串,很可能超过 50 字节。 错误的实现方式 常见代码如下: if (value.length() > 50) { value = value.substring(0, 50); } 这只能保证字符数,而无法保证字节数。 更严重的是,如果直接按字节截断,还可能: 截断多字节字符 生成非法 UTF-8 字符串 出现乱码或替换字符(�) 正确解决方案:按字节安全截断 正确做法必须满足: 遵守数据库的 字节限制 保证结果是 合法 UTF-8 字符串 不能截断一个字符的一部分 Java 实现(UTF-8安全截断) public static String truncateUtf8(String value, int maxBytes) { if (value == null) return null; byte[] bytes = value.getBytes(StandardCharsets.UTF_8); if (bytes.length <= maxBytes) return valu...