回 帖 发 新 帖 刷新版面

主题:获取URL信息出现FileNotFoundException异常

这是源代码: 
[code]
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()); 
      } 

[/code]
我将index.html放在和URLTest同一目录下了。可运行结果为何有FileNotFoundException异常?为何无法显示index.html这个页面? 如何解决,请指教
详细: 
D:\>javac URLTest.java 

D:\>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个回复)

沙发

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:8080/index.html");
            
            File file = new File(url.getFile().substring(1));
            //is = url.openStream();
            is = new FileInputStream(file);
            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());
    }
}

我来回复

您尚未登录,请登录后再回复。点此登录或注册