有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

读取第一行的java文本文件具有键和第二行前进值

****文本文件格式:****

FirstName,lastname,role,startdate,emptype
sreedhar,reddy,Admin,20-2-2018,contract
shekar,kumar,Admin,20-2-2018,contract
RAJ,roy,Admin,20-2-2018,contract
somu,reddy,Admin,20-2-2018,contract
sumanth,reddy,Admin,20-2-2018,contract

问题:

如何读取文本文件以及如何输入地图(键、值)

第一行在映射中有键(例如:firstname、lastname等)

地图中向前值的第二行(例如:sreedhar、reddy等)

映射输出:{Firstname:sreedhar,Lastname:reddy,role:Admin,startdat:2-6-2018}

请任何一个提供java代码的读取文本文件,并放入地图读取有键,值对


共 (2) 个答案

  1. # 1 楼答案

    您需要为Map指定不同的键,因为它每次都需要一个唯一的键:

    A map cannot contain duplicate keys; each key can map to at most one value.

    因此,您很可能需要MapMaps:

    在文件中读取:

    File file = new File("\\\\share\\path\\to\\file\\text.txt");
    

    添加到扫描仪:

    Scanner input = new Scanner(file);
    

    将第一行读作“标题”:

    String[] headerArray = input.nextLine().split(",");
    

    创建一个MapMap

    Map<String, Map<String, String>> myMap = new HashMap<>();
    

    循环遍历文本文件的其余部分,添加到Map,然后将Map添加到主Map,以及一个键(我使用了User0, User1...):

    int pos = 0;
    String user = "User";
    while (input.hasNextLine()) {
        Map<String, String> map = new HashMap<>();
        int loop = 0;
        String[] temp = input.nextLine().split(",");
        for (String temp1 : temp) {
            map.put(headerArray[loop], temp1);
            loop++;
        }
        myMap.put(user + " " + pos, map);
        pos++;
    }
    

    一旦你把它分解成步骤,生活就会变得更轻松

  2. # 2 楼答案

    你可以这样做-

    br = new BufferedReader(new FileReader("file.txt"));
            String line = br.readLine();
            String headerLine = line;
            List<String> headerList = Arrays.asList(headerLine.split(","));
            List<List<String>> valueListList = new ArrayList<List<String>>();
    
            while (line != null) {
                line = br.readLine();
                String valueLine = line;
                if(valueLine != null) {
                    List<String> valueList = Arrays.asList(valueLine.split(","));
                    valueListList.add(valueList);
                }
            }
    
            Map<String, List<String>> map = new HashMap<String, List<String>>();
            for(int i=0; i<headerList.size();i++){
                List<String> tempList = new ArrayList<String>();
                for(int j=0; j<headerList.size();j++){
                    tempList.add(valueListList.get(i).get(i));
                }
                map.put(headerList.get(i), tempList);
            }
            System.out.println(map);
    

    输出:

    {emptype=[contract, contract, contract, contract, contract], 
    startdate=[20-2-2018, 20-2-2018, 20-2-2018, 20-2-2018, 20-2-2018], 
    role=[Admin, Admin, Admin, Admin, Admin], 
    lastname=[kumar, kumar, kumar, kumar, kumar], 
    FirstName=[sreedhar, sreedhar, sreedhar, sreedhar, sreedhar]}