简体   繁体   English

从 Java 中的文件读取字符串时如何跳过字符

[英]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} ).所以,我想将这个词作为键和值存储在 map 中(例如: {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);
    }

Use the split method of String in Java.使用Java中Stringsplit方法。

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]);

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: 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 "=".例如, "\\n+|="将用一个或多个端线或“=”分割标记。 The end line is somewhat hard coded though so it could change depending on the platform the file was created on.结束行有些硬编码,因此它可能会根据创建文件的平台而改变。

A simple "if" condition will solve it.一个简单的“如果”条件将解决它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM