简体   繁体   English

Java程序Inetaddress

[英]java program Inetaddress

The question I have been asked is too write java program that reads IP address from input file and writes the corresponding host names in the output file and vice versa. 我被问到的问题也是编写Java程序,该程序从输入文件读取IP地址,并在输出文件中写入相应的主机名,反之亦然。 here is my code: 这是我的代码:

import java.net.*;
import java.io.*;
public class hw
{
    public static void main(String args[])
    {
        try{

        FileReader f= new FileReader("w.txt");

        BufferedReader  r = new BufferedReader(f);

        FileWriter  o = new FileWriter("out.txt");
        PrintWriter p = new PrintWriter(o);


        String line = r.readLine();
        String hn=line;
        String IP;
        InetAddress d=InetAddress.getByName(hn);
        while(line !=null)
        {
        hn=d.getByName(line);
                p.println(hn);
                IP=d.getHostName();
                 p.println(IP);



    }
        r.close();
        p.close();
          }
       catch(FileNotFoundException e )
        {System.out.println("file not found");}
        catch(IOException e)
        {System.out.println("io error "+e.getMessage());}
    }//main
}//class

I guess your while loop never terminates. 我猜你的while循环永远不会终止。 Usually I read in a loop like this: 通常我会像这样循环阅读:

while ((line = r.readLine()) != null) {
    // process line, i.e.
    InetAddress ia = InetAddress.getByName(line.trim());
    // etc.
}

Also you might consider putting your close statements into the finally block for good form. 另外,您也可以考虑将close语句放入finally块中以获得良好格式。

凯文纠正你的循环错误,因为你的第二个问题,我建议你阅读教程的读取和写入文件使用IO流

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

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