简体   繁体   中英

How Java extracts words from a text file?

I have a text file which contains data in one line, and I want to extract words from the text file.

The words I want to extract are: "id" and "token"

With Java I can read the file:

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class ReadStringFromFile
{
    public static void main(String[] args) throws IOException
    {
        File file = new File("test.txt");
        String string = FileUtils.readFileToString(file);
        System.out.println("Read in: " + string);
    }
}

As the text file is in one line, I do not know how I can extract a value from the String.

You need to split the string.

In your case I assume the words are separated by a whitespace so string.split("\\\\s+"); should to the trick.

It looks like you're trying to parse some json code. You could use a json parser (check out: http://www.json.org/java/ ) or if your needs are simple use a regex to extract the bits you want. Maybe something like:

    File file = new File("test.txt");
    String string = FileUtils.readFileToString(file);
    Pattern re = Pattern.compile("(?:,|\\{)?\"([^:]*)\":(\"[^\"]*\"|\\{[^}]*\\}|[^},]*}?)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
    Matcher m = re.matcher(string);

    // Create a map of all values
    Map<String, String> map = new HashMap<String, String>();
    String id = "NOT_FOUND";
    String token = "NOT_FOUND";
    while (m.find()) {
        map.put(m.group(1), m.group(2).replace("\"", ""));
        if (m.group(1).trim().equals("id")) {
            id = m.group(2).replace("\"", "");
        }
        if (m.group(1).equals("token")) {
            token = m.group(2).replace("\"", "");
        }
    }

    System.out.println("id = " + id + " : token = " + token);

    // or 
    System.out.println(map);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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