Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

第 16 章 Network

目录

16.1. URL
16.1.1. 获取路径/文件名
16.1.2. 打开 URL
16.2. 获取IP地址何机器名

Java 网络相关操作

16.1. URL

16.1.1. 获取路径/文件名

			
package cn.netkiller.test;

import java.net.URL;

public class Test {


    public Test() {
    }

    public static void main(String[] args) throws Exception {

        // url  object
        URL url = null;

        try {
            // create a URL
            url = new URL("http://oss.netkiller.cn/book/d730dfb8-1ef2-49af-a728-ff68dc7c9f6e/3.mp3");
            // display the URL
            System.out.println("URL=" + url);

            // display the  Path
            System.out.println("Path=" + url.getPath());
            System.out.println("File=" + url.getFile());
            System.out.println("directory=" + url.getFile().substring(0, url.getFile().lastIndexOf("/")));
            System.out.println("Filename=" + url.getFile().substring(url.getFile().lastIndexOf("/") + 1));

        }
        // if any error occurs
        catch (Exception e) {

            // display the error
            System.out.println(e);
        }

    }

}	
			
			

16.1.2. 打开 URL

			
import java.net.*;
import java.io.*;

public class URLReader {
    public static void main(String[] args) throws Exception {

        URL url = new URL("http://www.netkiller.cn/");
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

        String inputLine;
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
    }
}