从java中的txt文件中检索特定字符串

时间:2016-12-06 11:11:43

标签: java java-io

嘿,我有一个txt文件,我只想从中读取一个特定的字符串。  文件:

This Ticket Being Generated as You Confirm

Name    : John

Movie   : Batman

Location: MidVally

Time    : 7PM-9PM

Time    : 2

Seats   : [A-4, B-3, D-5, C-1, D-2, E-3]

UniqueID: Batman7PM-9PMMidVally

我只想检索UniqueID以将其保存在字符串中,在这种情况下,String UniqID =“Batman7PM-9PMMidVally”。任何想法如何实现它

3 个答案:

答案 0 :(得分:2)

public FileReader fr = new FileReader("path/to/your/file");
public BufferedReader br = new BufferedReader(fr);
String unique;
String line;
while((line =  br.readLine()) != null){
    if (line.contains("UniqueID"))
    {
        unique = line.split(":")[1].trim();
        break;
    }
}

如果文件始终具有相同的结构。

答案 1 :(得分:1)

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.stream.Stream;


public class TestClass {


    private static final String FILE_PATH = "YOUR-FILE-PATH";

    public static void main(String... a) {

        String uniqID = "";


        uniqID = getValueFromFile(FILE_PATH, "UniqueID");

        System.out.println("String UniqID = \"" + uniqID + "\"");

    }

    private static String getValueFromFile(String filePath, String id) {

        HashMap<String, String> map= readFile(filePath);
        String  value=searchMap(map,id);

        return value;


    }

    private static String searchMap(HashMap<String,String> map,String id) {


        try {

            if(map.containsKey(id))return map.get(id);

        }
        catch (Exception e){
            e.printStackTrace();

        }
        return "Not Found";

    }

    private static HashMap readFile(String filePath) {
        HashMap<String, String> map = new HashMap<>();
        try {

            try (Stream<String> lines = Files.lines(Paths.get(filePath), StandardCharsets.UTF_8)) {
                for (String line : (Iterable<String>) lines::iterator) {
                    String[] lineValues = line.split(":");
                    if (lineValues.length == 2)
                        map.put(lineValues[0].trim(), lineValues[1].trim());
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

}

答案 2 :(得分:0)

这是一个类似于json的结构,除了在您确认时生成此票证。尝试将该文本转换为json,然后尝试检索as键值对。