2011-03-07 24 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