spring boot 在 k8s 上 读取 resources 下 文件夹下的文件夹里的json 文件

22 阅读1分钟

只是一个普通的读取文件夹里的翻译文件,显示对应的国家的语言翻译结果

AI 生成的代码本地可以允许,上了k8s 里 读取不到

image.png

读取文件夹里的文件解决方法:



import org.springframework.core.io.Resource;

import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import org.springframework.core.io.support.ResourcePatternResolver;

ClassLoader classLoader = getClass().getClassLoader();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(classLoader);
Resource[] resources = resolver.getResources("classpath:widgetTranslation/*/*.json");
for (Resource resource : resources) {
    String jsonContent;
    try (InputStream inputStream = resource.getInputStream()) {
        jsonContent = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        // 文件内容
        JsonObject jsonContentObi = JsonParser.parseString(jsonContent).getAsJsonObject();

        String path = resource.getURL().getPath();
        String[] pathParts = path.split("/");
        String dirName = pathParts[pathParts.length - 2]; // 获取文件夹名称 am_ET
        String dirRegion = dirName.substring(dirName.indexOf('_') + 1); // ET

读取resources 下的json文件

InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("translation_merged.json");
BufferedReader reader = null;
if (in != null) {
    reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
}
StringBuilder content = new StringBuilder();
    String line;
if (reader != null) {
    while ((line = reader.readLine()) != null) {
        content.append(line);
    }
}
Map<String, String> mergedMap = new Gson().fromJson(content.toString(), Map.class);