知乎专栏 |
Java 网络相关操作
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); } } }
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(); } }