首页 > 解决方案 > how to skip a character when read strings from a file in Java

问题描述

For example, the content of a file is:

black=white

bad=good

easy=hard

So, I want to store in a map this words as key and value (ex: {black=white, bad=good} ). And my problem is when I read string I have to skip a char '=' which disappears key and value. How to make this?

In code below I make a code which read key and value from file, but this code works just when between words is SPACE, but I have to be '='.

System.out.println("File name:");
    String pathToFile = in.nextLine();
    File cardFile = new File(pathToFile);
    try(Scanner scanner = new Scanner(cardFile)){
        while(scanner.hasNext()) {
            key = scanner.next();
            value = scanner.next();
            flashCards.put(key, value);
        }
    }catch (FileNotFoundException e){
        System.out.println("No file found: " + pathToFile);
    }

标签: java

解决方案


使用Java中的split方法String

因此,在阅读您的行之后,拆分字符串并按原样获取键和值。

String[] keyVal = line.split("=");
System.out.println("key is ", keyVal[0]);
System.out.println("value is ", keyVal[1]);

推荐阅读