这是源代码:
import java.net.*;
import java.io.*;
public class URLTest {
public static void main(String[] args){
URL url=null;
InputStream is;
try{
url=new URL("http://localhost/index.html");
is=url.openStream();
int c;
try{
while((c=is.read())!=-1)
System.out.print((char)c);
}
catch(IOException e){}
finally{
is.close();
}
            }catch(MalformedURLException e){
 e.printStackTrace();
}catch(IOException e){
    e.printStackTrace();
}
       System.out.println("文件名:"+url.getFile());
       System.out.println("主机名:"+url.getHost());
       System.out.println("端口号:"+url.getPort());
       System.out.println("协议名:"+url.getProtocol());
      }
}我将index.html放在和URLTest同一目录下了。可运行结果为何有FileNotFoundException异常?为何无法显示index.html这个页面?
详细:
D:\>javac URLTest.javaD:\>java URLTest
java.io.FileNotFoundException: http://localhost/index.html
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLCo
nection.java:1239)
        at java.net.URL.openStream(URL.java:1009)
        at URLTest.main(URLTest.java:9)
文件名:/index.html
主机名:localhost
端口号:-1
协议名:http

解决方案 »

  1.   

    当然会出错了,你用了URL去访问呀,它是要用网络访问呀,你必须把index.html放到你本地的webserver的根目录,然后启动webserver才行呀
    你和URLTest放一个目录是没有用的呀
      

  2.   

    http://localhost/index.html这个是你发布web目录的根目录文件index.html
    跟你的程序完全没有关系随便改成网上的一个页面测试下
    http://hi.csdn.net/my.html
      

  3.   

    你如果要想用url访问本地的文件的话,就不能用http协议,http协议是用来访问web服务器上的文件的
    本地的要用这个url=new URL("file:///d:/index.html "); 
      

  4.   

    楼上说的对啊你如果想要用URL访问本地的文件,就不应该使用http协议!