这是源代码:
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
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
你和URLTest放一个目录是没有用的呀
跟你的程序完全没有关系随便改成网上的一个页面测试下
http://hi.csdn.net/my.html
本地的要用这个url=new URL("file:///d:/index.html ");