【问题标题】:converting InetAddress to string将 InetAddress 转换为字符串
【发布时间】:2015-01-17 21:13:50
【问题描述】:

我使用哈希表来保存文件名(字符串)和 InetAddress

Hashtable <String , InetAddress > file_location = new Hashtable <String , InetAddress >(); 

我使用它来检索地址,但我只返回一个空值

file_location.put("ABD_9158" , IPAddress); //IPAdress is of InetAddress type

 InetAddress n = file_location.get("ABD_9158");

        System.out.println(n);

尝试将 n 更改为字符串,但无法找到 我的问题,如何检索 IP 地址?

【问题讨论】:

  • 您可以在调试模式下运行程序并检查地图的状态。如果确实有一个键 ABD_9158 或与之对应的任何值。
  • @Amr Hamada 尝试打印你的 HashMap, System.out.println(fileLocation );
  • 当我使用 enumerate e = file_location.key();并打印出来,它返回 ABD_9158
  • @ankur-singhal 这是输出 {ABD_9158=/192.168.2.21}
  • 您已声明为 fileLocation,但之后使用了 file_location。希望这不是代码实际的样子。

标签: java string hashtable inetaddress


【解决方案1】:

这是一个小程序,用来检查你想要什么。同一段代码,你分享的,它工作正常。

 public static void main(String args[]) {
        Hashtable<String, InetAddress> fileLocation = new Hashtable<String, InetAddress>();
        InetAddress addr;
        try {
            addr = InetAddress.getByName("127.0.0.1");
            fileLocation.put("ABD_9158", addr); // IPAdress is of InetAddress type
            InetAddress n = fileLocation.get("ABD_9158");
            System.out.println(n);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

输出

/127.0.0.1

【讨论】:

  • 是的,实际上当我使用变量而不是“ABD_9158”时,我得到了正确的地址返回,你知道为什么会发生这种情况吗?我百分百确定我的书写正确并将其与变量匹配?
  • 我比较了两个字符串,变量和字符串“ABD_9158”,由于某种原因它们不一样
  • @AmrHamada 你是用== 还是equals 来比较,后者会给你正确的结果,以防你错过了
  • 不,我在使用equals,但它不起作用我也使用equalsIgnoreCase,如果这有助于我通过数据报套接字发送文件名并使用此行接收文件String file = new String( receivePacket.getData());
猜你喜欢
  • 2011-07-31
  • 2013-12-29
  • 2010-12-29
  • 1970-01-01
  • 2019-10-10
  • 2019-01-05
  • 2015-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多