如何在java中的.txt文件中选择一个键及其适当的值

时间:2017-02-08 06:03:25

标签: java hashmap

这是我的以下.txt文件

.txt file

我想基于URl检索IP地址。我尝试了以下代码,但它失败了。我可以使用Hashmap来做。这是我的第一篇文章。我为自己的错误道歉。

public static void main(String args [])抛出IOException {

    FileReader fr = new FileReader("C:/Users/charan/Desktop/Resources/HashCheck.txt");
    BufferedReader br = new BufferedReader(fr);
    Scanner in = new Scanner(System.in);
    System.out.println("enter:");
    String output = in.next();
    String line;

    while((line =  br.readLine()) != null){
        if (line.contains(output))
        {
            output = line.split(":")[1].trim();
            System.out.println(output);
            break;
        }
        else
            System.out.println("UrL not found");
        break;
    }
    in.close();

}}

1 个答案:

答案 0 :(得分:0)

public static void main(String args[]) throws IOException {

    FileReader fr = new FileReader("C:/Users/charan/Desktop/Resources/HashCheck.txt");
    BufferedReader br = new BufferedReader(fr);
    Scanner in = new Scanner(System.in);
    System.out.println("enter:");
    String output = in.next();
    String line;
    String myIp = null;                       //assign a new variable to put IP into
    while ((line = br.readLine()) != null) {
        if (line.contains(output)) {
            myIp = line.split(":")[1].trim(); //assign IP to the new variable
            System.out.println(myIp);
            break;                            //break only if you get the IP. else let it iterate over all the elements.
        }
    }
    in.close();
    if (myIp == null) {                      //if the new variable is still null, IP is not found
        System.out.println("UrL not found");
    }
}