Java程序实现多语言资源JSON文件生成

你好呀,我是小邹。

在现代软件开发中,实现应用程序的多语言支持是一项基本需求,以适应全球用户的语言环境。本文将介绍一段Java代码,其主要功能是生成一个特定格式的JSON文件,用于存储和管理中英文双语对照的键值对,从而为应用程序的国际化提供所需资源。

一、代码概述(源码在文末)

该代码位于包top.hqxiaozou.module.systemservice.zhen中,核心类为ExportZHAndENJson。程序的主要任务是:

  1. 构建键值对数据:创建一个List<KeyPair>,其中包含86个键值对实例,每个实例包含键名(key)、中文文本(zh)和英文文本(en)。
  2. 数据分组:按照预定义的索引范围,将键值对列表划分为六个逻辑分组。
  3. 生成JSON数组:对每个分组内的键值对进行JSON化处理,生成嵌套的JSONObject,并封装至JSONArray
  4. 导出JSON文件:将生成的六个顶级JSONArray写入到指定路径的JSON文件中。

二、关键类与方法

1. KeyPair类

KeyPair是一个简单数据类,用于封装键值对信息。其属性包括:

  • key: 字符串类型,作为键名,用于在应用程序中唯一标识一个文本资源。
  • zh: 字符串类型,中文文本。
  • en: 字符串类型,英文文本。
2. ExportZHAndENJson类

main方法:程序的入口点,负责整个流程的控制。

  • 数据初始化:定义一个包含86个键值对的列表,内容涵盖用户界面元素、设备交互、图形编辑等多个领域的文本资源。
  • 数据分组
    • 定义一个二维数组groupIndexRanges,表示每个分组所包含的键值对索引范围。
    • 构建一个HashMap<Integer, Integer>,将键值对索引映射到对应的分组编号。
    • 初始化一个List<List<KeyPair>>,用于存储分组后的键值对列表。
    • 遍历所有键值对,根据索引映射将其分配到相应的分组中。
  • JSON数组生成
    • 使用groupedPairs流式处理,调用createJSONArrayFromGroup方法将每个分组转换为JSONArray
    • 将六个分组的JSONArray收集到一个顶级JSONArray数组中。
  • 文件导出
    • 设置目标文件路径(默认为C:\Users\lenovo_ID3\Desktop\output.json)。
    • 调用createDirectoryIfNotExists方法确保目标目录存在,否则创建。
    • 使用FileWriter将顶级JSONArray数组写入到JSON文件中,并输出相关信息。

createJSONArrayFromGroup方法:私有辅助方法,接收一个键值对分组列表,将其转换为JSONArray

  • 对分组中的每个KeyPair,创建一个嵌套的JSONObject,结构为{"key": {"zh": "中文文本", "en": "English text"}}
  • 将所有此类JSONObject添加到JSONArray中,形成该分组的JSON表示。

createDirectoryIfNotExists方法:私有辅助方法,用于检查并创建目标目录。

  • 接收一个目录路径字符串。
  • 使用Paths.getFiles.exists检查目录是否存在。
  • 若不存在,则调用Files.createDirectories创建目标目录。

三、输出JSON文件结构与应用

生成的JSON文件由六个顶级JSONArray组成,每个数组代表一个分组的键值对集合。每个数组内部包含若干个嵌套的JSONObject,其结构如下:

1[
2  {
3    "key": {
4      "zh": "中文文本",
5      "en": "English text"
6    }
7  },
8  // ... 其他键值对
9]

在实际应用中,应用程序(如客户端或服务器端代码)会读取此JSON文件,根据用户选择的语言(如中文或英文)提取对应的文本资源。由于键值对按分组存储,便于管理和更新多语言资源,同时也利于程序按需或按模块加载资源,提高运行效率。

总结来说,这段Java代码实现了多语言键值对数据的构建、分组、JSON化以及文件导出,为应用程序的国际化提供了坚实的数据基础。通过合理的数据结构设计和文件组织方式,兼顾了多语言资源管理的便利性和程序性能。

package top.hqxiaozou.module.system.service.zhen;import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;import java.io.FileWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.*;/*** 生成指定格式的json文件并导出。* 注:导出的文件在C:\Users\lenovo_ID3\Desktop\文件夹下,按需修改。*/
public class ExportZHAndENJson {public static void main(String[] args) throws Exception {List<KeyPair> keyPairs = Arrays.asList(// 0 - 11new KeyPair("cancel", "取消", "cancel"),new KeyPair("Select all", "全选", "Select all"),new KeyPair("Deselect all", "取消全选", "Deselect all"),new KeyPair("Total", "总数", "Total"),new KeyPair("Delete", "删除", "Delete"),new KeyPair("Edit name", "修改名称", "Edit name"),new KeyPair("Finish", "完成", "Finish"),new KeyPair("Incremental save", "增量保存", "Incremental save"),new KeyPair("Full storage", "全量保存", "Full storage"),new KeyPair("No data", "暂无数据", "No data"),new KeyPair("Modify", "修改", "Modify"),new KeyPair("login with mobile", "手机号快捷登录", "login with mobile"),// 12 - 22new KeyPair("Please connect device", "暂无设备,请连接设备", "There is currently no device available, please connect the device"),new KeyPair("Connect Device", "连接设备", "Connect Device"),new KeyPair("Historical device", "历史设备", "Historical device"),new KeyPair("Discovered devices", "已发现x个设备", "x devices have been discovered"),new KeyPair("Add", "添加", "Add"),new KeyPair("Cancel Search", "取消搜索", "Cancel Search"),new KeyPair("Bluetooth", "蓝牙", "Bluetooth"),new KeyPair("No device", "没有搜索到设备", "No device found in search"),new KeyPair("Search again", "重新搜索", "Search again"),new KeyPair("Disconnect", "断开", "Disconnect"),new KeyPair("Device Settings", "设备设置", "Device Settings"),// 23 - 46new KeyPair("Color", "颜色", "Color"),new KeyPair("Choose a color", "选择一个颜色", "Choose a color"),new KeyPair("Geometry", "几何", "Geometry"),new KeyPair("Shape selection", "形状选择", "Shape selection"),new KeyPair("Typeface", "字体", "Typeface"),new KeyPair("Custom Text", "自定义文字", "Custom Text"),new KeyPair("Please enter text", "请输入文字", "Please enter text"),new KeyPair("Size", "大小", "Size"),new KeyPair("Accuracy", "精确度", "Accuracy"),new KeyPair("Spacing", "间距", "Spacing"),new KeyPair("Font direction", "字体方向", "Font direction"),new KeyPair("Font color", "字体颜色", "Font color"),new KeyPair("Please enter text first", "请先输入文字", "Please enter text first"),new KeyPair("Brush tools", "笔画", "Brush tools"),new KeyPair("Effect", "效果", "Effect"),new KeyPair("Set effect", "设置效果", "Set effect"),new KeyPair("Pattern 1", "图案1", "Pattern 1"),new KeyPair("Graphical Grouping", "图形分组", "Graphical Grouping"),new KeyPair("Graphical", "图形", "Graphical"),new KeyPair("Wave", "波浪", "Wave"),new KeyPair("point", "点", "point"),new KeyPair("Reset channel", "复位通道", "Reset channel"),new KeyPair("Please connect the device first", "请先连接设备", "Please connect the device first"),new KeyPair("Choose Gallery", "选择图库", "Choose Gallery"),// 47 - 54new KeyPair("My gallery", "我的图库", "My gallery"),new KeyPair("Play list", "播放列表", "Play list"),new KeyPair("Add Gallery", "图库新增", "Add Gallery"),new KeyPair("Gallery name", "图库名称", "Gallery name"),new KeyPair("Please enter the gallery name", "请输入图库名称", "Please enter the gallery name"),new KeyPair("Add List", "添加到列表", "Add List"),new KeyPair("Create List", "新建列表", "Create List"),new KeyPair("My content", "我的内容", "My content"),// 55 - 69new KeyPair("Add scene", "场景新增", "Add scene"),new KeyPair("Scene name", "场景名称", "Scene name"),new KeyPair("Please enter the scene name", "请输入场景名称", "Please enter the scene name"),new KeyPair("Select Scene", "选择场景", "Select Scene"),new KeyPair("Scene Editing", "场景编辑", "Scene Editing"),new KeyPair("Real-time Effect", "实时效果", "Real-time Effect"),new KeyPair("Effect List", "效果列表", "Effect List"),new KeyPair("default", "默认", "default"),new KeyPair("Add Theme", "新增主题", "Add Theme"),new KeyPair("Copy Theme", "复制主题", "Copy Theme"),new KeyPair("Delete theme", "删除主题", "Delete theme"),new KeyPair("Copy effect", "复制效果", "Copy effect"),new KeyPair("Delete effect", "删除效果", "Delete effect"),new KeyPair("Choose List", "选择列表", "Choose List"),new KeyPair("save", "保存", "save"),// 70 - 86new KeyPair("My scene", "我的场景", "My scene"),new KeyPair("Device scene", "设备场景", "Device scene"),new KeyPair("Scene List", "场景列表", "Scene List"),new KeyPair("Effect list", "效果列表", "Effect list"),new KeyPair("Default scene", "默认", "Default scene"),new KeyPair("Autonomous", "自走", "Autonomous"),new KeyPair("Autonomous Speed", "自走速度", "Autonomous Speed"),new KeyPair("Voice Control", "声控", "Voice Control"),new KeyPair("Sound Sensitivity", "声音灵敏度", "Sound Sensitivity"),new KeyPair("Select Playback", "选择播放", "Select Playback"),new KeyPair("x Selected", "已选x个", "x Selected"),new KeyPair("Select all Scene", "全选", "Select all Scene"),new KeyPair("Reverse selection", "反选", "Reverse selection"),new KeyPair("clean up", "清除", "clean up"),new KeyPair("Sequential playback", "顺序播放", "Sequential playback"),new KeyPair("Random Play", "随机播放", "Random Play"),new KeyPair("Single loop", "单曲循环", "Single loop"));// 定义每个分组包含的索引范围int[][] groupIndexRanges = {{0, 11}, // 第一分组包含索引0 - 11{12, 22}, // 第二分组包含索引12 - 22{23, 46}, // 第三分组包含索引23 - 46{47, 54}, // 第四分组包含索引47 - 54{55, 69}, // 第五分组包含索引55 - 69{70, 86}  // 第六分组包含索引70 - 86};// 初始化分组映射Map<Integer, Integer> indexToGroupMap = new HashMap<>();for (int i = 0; i < groupIndexRanges.length; i++) {int start = groupIndexRanges[i][0];int end = groupIndexRanges[i][1];for (int j = start; j <= end; j++) {indexToGroupMap.put(j, i);}}// 初始化分组列表List<List<KeyPair>> groupedPairs = new ArrayList<>();for (int i = 0; i < groupIndexRanges.length; i++) {groupedPairs.add(new ArrayList<>());}// 分配KeyPair到分组for (int i = 0; i < keyPairs.size(); i++) {KeyPair pair = keyPairs.get(i);int groupIndex = indexToGroupMap.getOrDefault(i, -1);if (groupIndex == -1) {throw new RuntimeException("Invalid index mapping for KeyPair at index " + i);}List<KeyPair> targetGroup = groupedPairs.get(groupIndex);targetGroup.add(pair);}JSONArray[] topLevelArray = groupedPairs.stream().map(ExportZHAndENJson::createJSONArrayFromGroup).toArray(JSONArray[]::new);String targetFolderPath = "C:\\Users\\lenovo_ID3\\Desktop\\";String fileName = "output.json";createDirectoryIfNotExists(targetFolderPath);String filePath = targetFolderPath + fileName;try (FileWriter fileWriter = new FileWriter(filePath)) {fileWriter.write(Arrays.toString(topLevelArray));System.out.println("JSON data written to " + filePath);System.out.println(LocalDateTime.now().toString().replace("T", " "));}}private static JSONArray createJSONArrayFromGroup(List<KeyPair> group) {JSONArray innerArray = new JSONArray();group.forEach(pair -> {try {JSONObject entry = new JSONObject().set(pair.key, new JSONObject().set("zh", pair.zh).set("en", pair.en));innerArray.put(entry);} catch (JSONException e) {throw new RuntimeException("Failed to create JSON entry for KeyPair", e);}});return innerArray;}static class KeyPair {String key;String zh;String en;KeyPair(String key, String zh, String en) {this.key = key;this.zh = zh;this.en = en;}}private static void createDirectoryIfNotExists(String directoryPath) throws Exception {Path path = Paths.get(directoryPath);if (!Files.exists(path)) {Files.createDirectories(path);}}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/1091.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Claude 3 Opus 效果是否真的可以超过GPT-4?

实测,不仅是超过,而且我个人感觉这个差距甚至大于GPT3.5到GPT4的距离. claude3在长篇理学论文的解析能力是非常显著的,可以扩展补完作者省略的大量运用高等数学,复变函数以及更多数理方法的计算过程,并且将中间过程补完的非常完美.不会漏符号,错符号,偏差数值之类的问题.工科许…

ModuleNotFoundError: No module named ‘cv2‘

python运行到下面这一句“import cv2”时报错&#xff1a; >>> import cv2 Traceback (most recent call last):File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named cv2 解决方法&#xff1a; 安装扩展包&#xff0…

基于K-prototype算法聚类

k-prototype聚类是一种用于混合数据类型聚类的算法&#xff0c;由Jain和Dubes在1988年提出。它主要用于同时包含连续属性和离散属性的数据集。k-prototype算法可以看作是k-means算法的扩展&#xff0c;它将k-means算法的思想应用于混合数据类型&#xff0c;通过为连续属性和离散…

ubuntu在xshell中使用快捷方式操作命令,减少命令行的数入量

第一步 第二步 然后无脑确定 第三步 在xshell的显示方式 方式一 这样就会在每个窗格中进行显示 方式二 效果显示–> 这种窗格的显示是全局的 然后你双击这个process就会自动把命令打在命令行上&#xff0c;减少你的输入量

Oracle数据库Bug:相关子查询多层嵌套报错:标识符无效

Oracle Bug? 一、案例描述二、解决方案<一>、升级版本<二>、改写语句 一、案例描述 在Mysql中常常有如下写法用相关子查询 order by desc limit 1来完成需求 select code,date,(select value from test t1 where t.code t1.code and t1.date between date_su…

【Gradle如何安装配置及使用的教程】

&#x1f3a5;博主&#xff1a;程序员不想YY啊 &#x1f4ab;CSDN优质创作者&#xff0c;CSDN实力新星&#xff0c;CSDN博客专家 &#x1f917;点赞&#x1f388;收藏⭐再看&#x1f4ab;养成习惯 ✨希望本文对您有所裨益&#xff0c;如有不足之处&#xff0c;欢迎在评论区提出…

新型大数据架构之湖仓一体(Lakehouse)架构特性说明——Lakehouse 架构(一)

文章目录 为什么需要新的数据架构&#xff1f;湖仓一体&#xff08;Lakehouse&#xff09;——新的大数据架构模式同时具备数仓与数据湖的优点湖仓一体架构存储层计算层 湖仓一体特性单一存储拥有数据仓库的查询性能存算分离开放式架构支持各种数据源类型支持各种使用方式架构简…

递归求阶乘和(不熟悉)

本题要求实现一个计算非负整数阶乘的简单函数&#xff0c;并利用该函数求 1!2!3!...n! 的值。 函数接口定义&#xff1a; double fact( int n ); double factsum( int n ); 函数fact应返回n的阶乘&#xff0c;建议用递归实现。函数factsum应返回 1!2!...n! 的值。题目保证输…

快速访问github

修改本地hosts文件 GitHub访问慢的原因在于域名解析&#xff0c;通过修改本地的hosts文件&#xff0c;将远程DNS解析改为本地DNS解析。 fang 步骤1&#xff1a;打开hosts文件&#xff08;没有就创建&#xff09; host所在位置&#xff1a; C:\Windows\System32\drivers\etc…

1031:反向输出一个三位数

#include<bits/stdc.h> using namespace std; int main() {int a;cin>>a;cout<<a%10;cout<<a/10%10;cout<<a/100%10;return 0; } 时间限制: 1000 ms 内存限制: 65536 KB 提交数:146171 通过数: 89399 【题目描述】 将一个三位数反向…

linux@内核@内核版本发展@镜像文件查看内核

文章目录 linux内核介绍简介小结 linux发行版和内核各个linux发行版和内核的关系内核更新追踪GAHWE版的内核 内核版本查看&#x1f60a;linux当前系统内核查看未安装时查看网络搜索内核版本号挂载镜像查看虚拟机启动镜像体验版查看内核版本 linux(内核)版本演进&#x1f60a;相…

python_列表和元组

介绍 列表&#xff08;List&#xff09;和元组&#xff08;Tuple&#xff09;是Python中两种不同的数据结构&#xff0c;它们都可以用来存储一系列的元素。下面是它们的主要特点和区别&#xff1a; 列表&#xff08;List&#xff09; 可变性&#xff1a;列表是可变的&…

【c基础】文件操作

1.fopen和fclose函数 函数原型 FILE *fopen(const char *path, const char *mode); 参数解释&#xff1a; 返回值&#xff1a;fopen打开成功&#xff0c;则返回有效file的有效地址&#xff0c;失败返回NULL。path是文件路径&#xff0c;可以相对路径&#xff0c;可以绝对路径…

C# 将 TextBox 绑定为 KindEditor 富文本

目录 关于 KindEditor 绑定设计 部署 KindEditor 实现代码 小结 关于 KindEditor KindEditor 基于JavaScript 编写&#xff0c;可以与众多WEB应用程序结合。KindEditor 依靠出色的用户体验和领先的技术提供富文本编辑功能&#xff0c;是一款非常受欢迎的HTML在线编辑器。…

400电话如何对接配置SIP

400电话对接配置SIP的基本步骤 要配置400电话对接SIP&#xff0c;通常需要遵循以下基本步骤&#xff1a; 注册和认证&#xff1a;首先需要在相应的云通信平台上注册账号&#xff0c;并进行企业实名认证。 开通语音服务&#xff1a;在通过认证后&#xff0c;需要开通语音服务&…

(007)Blender 根据顶点组分离模型

1.选中模型&#xff0c;并且进入【3D视图】【编辑模式】&#xff1a; 2.选择顶点组&#xff1a; 3.分离选中项&#xff1a;

【经验总结】Jupyter 配置内核

1. 背景描述 使用 国家超算互联网中心 的服务器&#xff0c;创建 jupyterlab 容器&#xff0c;想在之前 conda 创建的环境中运行&#xff0c;可是不行&#xff0c;进入容器就直接进入 jupyterlab 2. 解决方法 配置内核 2.1 激活环境 conda activate peft2.2 安装内核 pip…

易保全网络赋强公证系统,前置预防、快速化解债权纠纷

网络赋强公证是一种创新的法律服务模式&#xff0c;为金融机构和债权人提供了一种便捷、高效的债权保障方式。既可以加大对违约方的司法震慑力&#xff0c;又能降低维权方实现债权的风险&#xff0c;且执行时间更快&#xff0c;债权周期更短&#xff0c;诉讼费用更低&#xff0…

Oracle函数

Oracle 函数 一、SQL函数分类 二、单行函数字符函数数字函数日期函数转换函数to_charto_numberto_date 其它函数单行函数嵌套 三、组函数数据分组创建分组过滤分组&#xff08;having子句&#xff09;分组和排序 Selecct子句顺序 一、SQL函数 函数一般是在数据上执行的&#x…

AttributeError: can‘t set attribute ‘lines‘

目录 报错代码&#xff1a; 解决方法&#xff1a; 示例完整代码&#xff1a; 报错代码&#xff1a; ax.lines [] 解决方法&#xff1a; 当你尝试使用 ax.lines [] 来清除一个图表的线条&#xff0c;并遇到 AttributeError: cant set attribute 错误时&#xff0c;这表明…