2011-03-07 40 views
0

我一直在問的問題太 寫java程序,它從輸入文件中讀取IP地址,並在輸出文件中寫入相應的主機名,反之亦然。 這裏是我的代碼:java程序Inetaddress

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 
+2

,什麼是你的問題?這是否編譯?它是否會拋出異常?它工作嗎? – 2011-03-07 15:21:08

回答

0

我想你的while循環永遠不會終止。通常我在這樣的循環中讀取:

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

你也可以考慮把你的親密語句進入finally塊的好形式。

+0

ok thnx實際上你幫助解決了其中一個問題..但是現在它不是在文件輸出文件輸出文件仍然是空的後運行程序我改變,而這樣: – lona 2011-03-07 16:20:00

+0

while((line = r.readLine() )!= null){ \t \t // process line,ie \t \t InetAddress d = InetAddress.getByName(line.trim()); p.println(d.getByName(line)); } – lona 2011-03-07 16:20:22

0

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