我被问到的问题是,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发布于 2011-03-07 23:22:38
我猜你的while循环永远不会结束。通常我会像这样循环阅读:
while ((line = r.readLine()) != null) {
// process line, i.e.
InetAddress ia = InetAddress.getByName(line.trim());
// etc.
}此外,您可以考虑将close语句放入finally块中,以获得良好的格式。
发布于 2011-03-08 01:21:37
凯文纠正了您的循环错误,至于您的第二个问题,我建议您阅读this教程,了解如何使用流io读写文件
https://stackoverflow.com/questions/5221356
复制相似问题