You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java如何将文本文件中读取的字符串转换为变量标识符使用

Java作为静态编译型语言,不支持在运行时用字符串动态声明新变量,所有变量名必须在编译阶段就确定,所以你没法直接生成叫Jerry、Jeff的变量直接调用。但完全可以用Map结构模拟这个效果,不需要硬编码case语句,后续调用也很方便。

实现思路

  • 用HashMap<String, List<String>>作为存储容器,键就是~后面的用户名,值就是对应用户名下的所有路径行。如果需要存储处理后的数值,也可以把值的类型换成List<Integer>或者int[]。
  • 读取文件的时候每次遇到~开头的行,就把当前处理的键切换为该行去掉~后的内容,后续非~开头的行都存入当前键对应的列表里。

可运行示例代码

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FileParseDemo {
    public static void main(String[] args) {
        String filepath = "替换为你的文件实际路径";
        // 存储结构:key为~后面的用户名,value为对应用户的所有路径行
        Map<String, List<String>> userPathMap = new HashMap<>();
        // 记录当前正在处理的用户名
        String currentUser = null;

        try(BufferedReader br = new BufferedReader(new FileReader(filepath))) {
            String line;
            while((line = br.readLine()) != null) {
                line = line.trim();
                // 跳过空行
                if(line.isEmpty()) continue;
                if(line.startsWith("~")){
                    // 提取用户名,更新当前处理的用户
                    currentUser = line.substring(1);
                    // 对应用户的列表不存在就初始化
                    userPathMap.putIfAbsent(currentUser, new ArrayList<>());
                } else if(currentUser != null){
                    // 把当前行加入对应用户的列表
                    userPathMap.get(currentUser).add(line);
                }
            }
        } catch(Exception e){
            e.printStackTrace();
        }

        // 后续调用示例:获取Jerry的所有路径
        List<String> jerryPaths = userPathMap.get("Jerry");
        if(jerryPaths != null){
            for(String path : jerryPaths){
                System.out.println("Jerry的路径:" + path);
            }
        }

        // 遍历所有用户的内容也很方便
        for(Map.Entry<String, List<String>> entry : userPathMap.entrySet()){
            System.out.println("用户" + entry.getKey() + "的所有路径:");
            entry.getValue().forEach(System.out::println);
        }
    }
}

这种实现方式灵活性很高,哪怕后续文件里新增了其他用户名,代码完全不用修改就能自动适配,不需要额外加case分支。

内容的提问来源于stack exchange,提问作者veila

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 08:36:05