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 - 11
                new 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 - 22
                new 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 - 46
                new 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 - 54
                new 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 - 69
                new 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 - 86
                new 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);
        }
    }

}
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值