簡體   English   中英

Java程序Inetaddress

[英]java program Inetaddress

我被問到的問題也是編寫Java程序,該程序從輸入文件讀取IP地址,並在輸出文件中寫入相應的主機名,反之亦然。 這是我的代碼:

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

我猜你的while循環永遠不會終止。 通常我會像這樣循環閱讀:

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

另外,您也可以考慮將close語句放入finally塊中以獲得良好格式。

凱文糾正你的循環錯誤,因為你的第二個問題,我建議你閱讀教程的讀取和寫入文件使用IO流

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM