0

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);
    }
1
  • 3
    What about reading a whole line at a time and splitting it with "=" character? Commented Jul 22, 2020 at 6:32

3 Answers 3

3

Use the split method of String in Java.

so after reading your line, split the string and take the key and value as so.

String[] keyVal = line.split("=");
System.out.println("key is ", keyVal[0]);
System.out.println("value is ", keyVal[1]);
Sign up to request clarification or add additional context in comments.

Comments

1

You can change the delimiter for the scanner.

public static void main (String[] args) throws java.lang.Exception
{
    String s = "black=white\nbad=good\neasy=hard";
    Scanner scan = new Scanner(s);
    scan.useDelimiter("\\n+|=");
    while(scan.hasNext()){
        
        String key = scan.next();
        String value = scan.next();
        System.out.println(key + ", " + value);
    }
}

The output:

black, white
bad, good
easy, hard

Changing the delimiter can be tricky, and it could be better to just read each line,then parse it. For example, "\\n+|=" will split the tokens by either one or more endlines, or an "=". The end line is somewhat hard coded though so it could change depending on the platform the file was created on.

Comments

-1

A simple "if" condition will solve it.

if (key == '='){ break;}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.