Java Tutorial/Network/URL
Содержание
- 1 A class that displays information about a URL
- 2 Add Parameter to URL
- 3 Build query string for URL
- 4 Create a URL that refers to a jar file in the file system
- 5 Create a URL that refers to an entry in the jar file
- 6 Create BufferedInputStream from URL
- 7 Creating a URL with a single string.
- 8 Creating a URL With components
- 9 Eliminate Query
- 10 Extracts the base URL from the given URL by stripping the query and anchor part.
- 11 File size from URL
- 12 Get Content from a URL
- 13 Getting a Jar File Using a URL
- 14 Getting an Image from a URL
- 15 Getting Text from a URL
- 16 java.net.URL
- 17 Locating files by path or URL
- 18 Make a URL from the given string
- 19 new URL("mailto:your@yourserver.net")
- 20 Parse Host
- 21 Parse Port
- 22 Parsing a URL
- 23 ProtocolTester
- 24 provides a simple interface for assembling GET URLs
- 25 Read from URL
- 26 Reading A Web Resource: Opening a URL"s stream
- 27 Relative URL
- 28 Resolve a relative URL
- 29 Returns the anchor value of the given URL
- 30 Returns true if the URL represents a path, and false otherwise.
- 31 Save binary file from URL
- 32 URL Equality
- 33 URL Splitter
- 34 Utility to convert File to URL.
A class that displays information about a URL
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
/**
* A class that displays information about a URL.
*/
public class GetURLInfo {
/** Use the URLConnection class to get info about the URL */
public static void printinfo(URL url) throws IOException {
URLConnection c = url.openConnection(); // Get URLConnection from URL
c.connect(); // Open a connection to URL
// Display some information about the URL contents
System.out.println(" Content Type: " + c.getContentType());
System.out.println(" Content Encoding: " + c.getContentEncoding());
System.out.println(" Content Length: " + c.getContentLength());
System.out.println(" Date: " + new Date(c.getDate()));
System.out.println(" Last Modified: " + new Date(c.getLastModified()));
System.out.println(" Expiration: " + new Date(c.getExpiration()));
// If it is an HTTP connection, display some additional information.
if (c instanceof HttpURLConnection) {
HttpURLConnection h = (HttpURLConnection) c;
System.out.println(" Request Method: " + h.getRequestMethod());
System.out.println(" Response Message: " + h.getResponseMessage());
System.out.println(" Response Code: " + h.getResponseCode());
}
}
/** Create a URL, call printinfo() to display information about it. */
public static void main(String[] args) {
try {
printinfo(new URL(args[0]));
} catch (Exception e) {
System.err.println(e);
System.err.println("Usage: java GetURLInfo <url>");
}
}
}
Add Parameter to URL
/**********************************************************************************
* $URL: https://source.sakaiproject.org/svn/portal/branches/sakai_2-5-4/portal-util/util/src/java/org/sakaiproject/portal/util/URLUtils.java $
* $Id: URLUtils.java 28982 2007-04-16 21:41:44Z ian@caret.cam.ac.uk $
***********************************************************************************
*
* Copyright (c) 2006 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* @author ieb
* @since Sakai 2.4
* @version $Rev: 28982 $
*/
public class URLUtils
{
public static String addParameter(String URL, String name, String value)
{
int qpos = URL.indexOf("?");
int hpos = URL.indexOf("#");
char sep = qpos == -1 ? "?" : "&";
String seg = sep + encodeUrl(name) + "=" + encodeUrl(value);
return hpos == -1 ? URL + seg : URL.substring(0, hpos) + seg
+ URL.substring(hpos);
}
/**
* The same behaviour as Web.escapeUrl, only without the "funky encoding" of
* the characters ? and ; (uses JDK URLEncoder directly).
*
* @param toencode
* The string to encode.
* @return <code>toencode</code> fully escaped using URL rules.
*/
public static String encodeUrl(String url)
{
try
{
return URLEncoder.encode(url, "UTF-8");
}
catch (UnsupportedEncodingException uee)
{
throw new IllegalArgumentException(uee);
}
}
}
Build query string for URL
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class MainClass {
public static void main(String[] args) {
QueryString qs = new QueryString("pg", "q");
qs.add("kl", "XX");
qs.add("stype", "stext");
qs.add("q", "+\"Java Programming\"");
String url = "http://www.java.ru/query?" + qs;
System.out.println(url);
}
}
class QueryString {
private String query = "";
public QueryString(String name, String value) {
encode(name, value);
}
public void add(String name, String value) {
query += "&";
encode(name, value);
}
private void encode(String name, String value) {
try {
query +=URLEncoder.encode(name, "UTF-8");
query += "=";
query += URLEncoder.encode(value, "UTF-8");
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException("Broken VM does not support UTF-8");
}
}
public String getQuery() {
return query;
}
public String toString() {
return getQuery();
}
}
http://www.java.ru/query?pg=q&kl=XX&stype=stext&q=%2B%22Java+Programming%22
Create a URL that refers to a jar file in the file system
import java.net.URL;
public class Main {
public static void main(String[] argv) throws Exception {
URL url = new URL("jar:file:/c://my.jar!/");
}
}
Create a URL that refers to an entry in the jar file
import java.net.URL;
public class Main {
public static void main(String[] argv) throws Exception {
URL url = new URL("jar:file:/c://my.jar!/com/mycompany/MyClass.class");
}
}
Create BufferedInputStream from URL
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainClass {
public static void main(String[] args) throws Exception {
URL u = new URL("http://www.jexp.ru");
HttpURLConnection uc = (HttpURLConnection) u.openConnection();
int code = uc.getResponseCode();
String response = uc.getResponseMessage();
System.out.println("HTTP/1.x " + code + " " + response);
for (int j = 1;; j++) {
String header = uc.getHeaderField(j);
String key = uc.getHeaderFieldKey(j);
if (header == null || key == null)
break;
System.out.println(uc.getHeaderFieldKey(j) + ": " + header);
}
InputStream in = new BufferedInputStream(uc.getInputStream());
Reader r = new InputStreamReader(in);
int c;
while ((c = r.read()) != -1) {
System.out.print((char) c);
}
}
}
Creating a URL with a single string.
import java.net.URL;
public class Main {
public static void main(String[] argv) throws Exception {
URL url = new URL("http://hostname:80/index.html");
}
}
Creating a URL With components
import java.net.URL;
public class Main {
public static void main(String[] argv) throws Exception {
URL url = new URL("http", "hostname", 80, "index.html");
}
}
Eliminate Query
public class Utils {
/**
* @param uri
* @return
*/
static public String eliminateQuery(String uri) {
int idx = uri.indexOf("?");
if (idx < 0) return uri;
return uri.substring(0, idx);
}
}
Extracts the base URL from the given URL by stripping the query and anchor part.
public class Utils {
public static final String QUERY_CHAR = "?"; //$NON-NLS-1$
public static final String ANCHOR_CHAR = "#"; //$NON-NLS-1$
/**
* Extracts the base URL from the given URL by stripping the query and anchor
* part.
*
* @param url
* URL
* @return URL without the query part
*/
public static String extractBaseUrl(String url) {
if (url != null) {
int queryPosition = url.indexOf(QUERY_CHAR);
if (queryPosition <= 0) {
queryPosition = url.indexOf(ANCHOR_CHAR);
}
if (queryPosition >= 0) {
url = url.substring(0, queryPosition);
}
}
return url;
}
}
File size from URL
import java.net.URL;
import java.net.URLConnection;
public class Main {
public static void main(String[] argv) throws Exception {
int size;
URL url = new URL("http://www.server.ru");
URLConnection conn = url.openConnection();
size = conn.getContentLength();
if (size < 0)
System.out.println("Could not determine file size.");
else
System.out.println(size);
conn.getInputStream().close();
}
}
Get Content from a URL
import java.net.URL;
public class MainClass {
public static void main(String[] args) {
try {
URL u = new URL("http://www.jexp.ru");
Object o = u.getContent();
System.out.println("I got a " + o.getClass().getName());
} catch (Exception ex) {
System.err.println(ex);
}
}
}
Getting a Jar File Using a URL
import java.net.URL;
public class Main {
public static void main(String[] argv) throws Exception {
// Create a URL that refers to a jar file on the net
URL url = new URL("jar:http://hostname/my.jar!/");
}
}
Getting an Image from a URL
import java.awt.Image;
import java.awt.Toolkit;
import java.net.URL;
public class Main {
public static void main(String[] argv) throws Exception {
URL url = new URL("http://hostname:80/image.gif");
Image image = Toolkit.getDefaultToolkit().getDefaultToolkit().createImage(url);
}
}
Getting Text from a URL
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
public class Main {
public static void main(String[] argv) throws Exception {
URL url = new URL("http://hostname:80/index.html");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
}
}
java.net.URL
A URL is a unique address to an Internet resource. Here is a URL: http://www.jexp.ru:80/index.htm
- HTTP: the protocol to use to retrieve the resource.
- http://www.yahoo.ru/: the host, where the resource resides.
- 80 is the port number.
- /index.htm specifies the path of the URL.
In Java, a URL is represented by a java.net.URL object.
public URL (java.lang.String spec)
public URL (java.lang.String protocol, java.lang.String host,java.lang.String file)
public URL (java.lang.String protocol, java.lang.String host,int port, java.lang.String file)
public URL (URL context, String spec)
Locating files by path or URL
/*
* JBoss, Home of Professional Open Source
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
* (C) 2005-2006,
* @author JBoss Inc.
*/
/*
* Copyright (C) 1998, 1999, 2000, 2001,
*
* Arjuna Solutions Limited,
* Newcastle upon Tyne,
* Tyne and Wear,
* UK.
*
* $Id: FileLocator.java 2342 2006-03-30 13:06:17Z $
*/
import java.io.File;
import java.net.URL;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
/**
* The FileLocator class provides a common method for locating files.
* If not passed an absolute filename (starting with the string "abs://"),
* it searches for the file in the order:
* in the directory specified by the system property user.dir
* in the directory specified by the system property user.home
* in the directory specified by the system property java.home
* using the getResource() method
*
* @author Julian Coleman
* @version $Id: FileLocator.java 2342 2006-03-30 13:06:17Z $
* @since JTS 3.0.
*/
public class FileLocator
{
/**
* Locate the specific file.
* Return the (URL decoded) abolute pathname to the file or null.
*/
public static String locateFile (String findFile) throws FileNotFoundException
{
URL url;
String fullPathName;
StringBuffer decodedPathName;
int pos, len, start;
if (findFile == null)
throw new FileNotFoundException("locateFile: null file name");
if (findFile.startsWith(absolutePath))
return findFile.substring(absolutePath.length());
if ((fullPathName = locateByProperty(findFile)) != null)
return fullPathName;
if ((url = locateByResource(findFile)) != null)
{
/*
* The URL that we receive from getResource /might/ have " "
* (space) characters converted to "%20" strings. However,
* it doesn"t have other URL encoding (e.g "+" characters are
* kept intact), so we"ll just convert all "%20" strings to
* " " characters and hope for the best.
*/
fullPathName = url.getFile();
pos = 0;
len = fullPathName.length();
start = 0;
decodedPathName = new StringBuffer();
while ((pos = fullPathName.indexOf(pct20, start)) != -1) {
decodedPathName.append(fullPathName.substring(start, pos));
decodedPathName.append(" ");
start = pos + pct20len;
}
if (start < len)
decodedPathName.append(fullPathName.substring(start, len));
fullPathName=decodedPathName.toString();
if (platformIsWindows())
fullPathName = fullPathName.substring(1, fullPathName.length());
return fullPathName;
}
throw new FileNotFoundException("locateFile: file not found: " + findFile);
}
/**
* Locate the specific file.
* Return the file name in URL form or null.
*/
public static URL locateURL (String findFile) throws FileNotFoundException
{
URL url;
String fullPathName;
if (findFile == null)
throw new FileNotFoundException("locateURL: null file name");
try {
if (findFile.startsWith(absolutePath))
{
return (new URL("file:/" + findFile.substring(absolutePath.length())));
}
if ((fullPathName = locateByProperty(findFile)) != null)
{
if(platformIsWindows())
url = new URL("file:/" + fullPathName);
else
url = new URL("file:" + fullPathName);
return url;
}
//TODO: TR: used for testing: return new URL(findFile);
}
catch (MalformedURLException e)
{
System.err.println("locateURL: URL creation problem");
throw new FileNotFoundException("locateURL: URL creation problem");
}
if ((url = locateByResource(findFile)) != null)
return url;
throw new FileNotFoundException("locateURL: file not found: " + findFile);
}
/**
* Search for a file using the properties: user.dir, user.home, java.home
* Returns absolute path name or null.
*/
private static synchronized String locateByProperty(String findFile)
{
String fullPathName = null;
String dir = null;
File f = null;
if (findFile == null)
return null;
try
{
// System.err.println("Searching in user.dir for: " + findFile);
dir = System.getProperty("user.dir");
if (dir != null) {
fullPathName = dir + File.separatorChar + findFile;
f = new File(fullPathName);
}
if (f != null && f.exists())
{
// System.err.println("Found in user.dir");
return fullPathName;
}
dir = System.getProperty("user.home");
if (dir != null) {
fullPathName = dir + File.separatorChar + findFile;
f = new File(fullPathName);
}
if (f != null && f.exists())
{
// System.err.println("Found in user.home");
return fullPathName;
}
dir = System.getProperty("java.home");
if (dir != null) {
fullPathName = dir + File.separatorChar + findFile;
f = new File(fullPathName);
}
if (f != null && f.exists())
{
// System.err.println("Found in java.home");
return fullPathName;
}
}
catch (Exception e)
{
return null;
}
return null;
}
/**
* Search for a file using the properties: user.dir, user.home, java.home
* Returns URL or null.
*/
private static URL locateByResource(String findFile)
{
ClassLoader loader = Thread.currentThread().getContextClassLoader();
URL url = loader.getResource(findFile);
if (url == null)
{
url = FileLocator.class.getResource("/" + findFile);
}
// System.err.println("Search succeeded via getResource()");
return url;
}
/*
* Check the file separator to see if we"re on a Windows platform.
*
* @return boolean True if the platform is Windows, false otherwise.
*/
private static boolean platformIsWindows()
{
if(File.separatorChar == "\\")
{
return true;
}
return false;
}
private static final String absolutePath = "abs://";
private static final String pct20 = "%20";
private static final int pct20len = 3;
}
Make a URL from the given string
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Map;
/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
public class Main{
/**
* Make a URL from the given string.
*
* <p>
* If the string is a properly formatted file URL, then the file
* portion will be made canonical.
*
* <p>
* If the string is an invalid URL then it will be converted into a
* file URL.
*
* @param urlspec The string to construct a URL for.
* @param relativePrefix The string to prepend to relative file
* paths, or null to disable prepending.
* @return A URL for the given string.
*
* @throws MalformedURLException Could not make a URL for the given string.
*/
public static URL toURL(String urlspec, final String relativePrefix) throws MalformedURLException
{
urlspec = urlspec.trim();
URL url;
try
{
url = new URL(urlspec);
if (url.getProtocol().equals("file"))
{
url = makeURLFromFilespec(url.getFile(), relativePrefix);
}
}
catch (Exception e)
{
// make sure we have a absolute & canonical file url
try
{
url = makeURLFromFilespec(urlspec, relativePrefix);
}
catch (IOException n)
{
//
// jason: or should we rethrow e?
//
throw new MalformedURLException(n.toString());
}
}
return url;
}
public static URI toURI(String urispec, final String relativePrefix)
throws URISyntaxException
{
urispec = urispec.trim();
URI uri;
if( urispec.startsWith("file:") )
{
uri = makeURIFromFilespec(urispec.substring(5), relativePrefix);
}
else
{
uri = new URI(urispec);
}
return uri;
}
/** A helper to make a URL from a filespec. */
private static URL makeURLFromFilespec(final String filespec, final String relativePrefix)
throws IOException
{
// make sure the file is absolute & canonical file url
File file = new File(decode(filespec));
// if we have a prefix and the file is not abs then prepend
if (relativePrefix != null && !file.isAbsolute())
{
file = new File(relativePrefix, filespec);
}
// make sure it is canonical (no ../ and such)
file = file.getCanonicalFile();
return file.toURI().toURL();
}
private static String decode(String filespec)
{
try
{
return URLDecoder.decode(filespec, "UTF-8");
}
catch (UnsupportedEncodingException e)
{
throw new RuntimeException("Error decoding filespec: " + filespec, e);
}
}
private static URI makeURIFromFilespec(final String filespec, final String relativePrefix)
{
// make sure the file is absolute & canonical file url
File file = new File(decode(filespec));
// if we have a prefix and the file is not abs then prepend
if (relativePrefix != null && !file.isAbsolute())
{
file = new File(relativePrefix, filespec);
}
return file.toURI();
}
/**
* Make a URL from the given string.
*
* @see #toURL(String,String)
*
* @param urlspec The string to construct a URL for.
* @return A URL for the given string.
*
* @throws MalformedURLException Could not make a URL for the given string.
*/
public static URL toURL(final String urlspec) throws MalformedURLException
{
return toURL(urlspec, null);
}
/**
*
* @param urispec
* @return the uri
* @throws URISyntaxException for any error
*/
public static URI toURI(final String urispec)
throws URISyntaxException
{
return toURI(urispec, null);
}
}
new URL("mailto:your@yourserver.net")
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
public class MainClass {
public static void main(String[] args) {
try {
URL u = new URL("mailto:your@yourserver.net");
URLConnection uc = u.openConnection();
uc.setDoOutput(true);
uc.connect();
OutputStream out = uc.getOutputStream();
for (int c = System.in.read(); c != -1; c = System.in.read()) {
out.write(c);
}
out.close();
} catch (IOException ex) {
System.err.println(ex);
}
}
}
Parse Host
public class Utils {
/**
* @param hostStr
* @return
*/
static public String parseHost(String hostStr) {
int sepIdx = hostStr.indexOf(":");
if (sepIdx < 0) {
return hostStr;
} else {
return hostStr.substring(0, sepIdx);
}
}
}
Parse Port
public class Utils {
/**
* @param hostStr
* @param defaultPort
* @return
*/
static public int parsePort(String hostStr, int defaultPort) {
int sepIdx = hostStr.indexOf(":");
if (sepIdx < 0) {
return defaultPort;
} else {
String portStr = hostStr.substring(sepIdx + 1).trim();
try {
return Integer.parseInt(portStr);
} catch (NumberFormatException e) {
return defaultPort;
}
}
}
}
Parsing a URL
You can retrieve the various components of a URL object by using these methods:
public java.lang.String getFile ()
public java.lang.String getHost ()
public java.lang.String getPath ()
public int getPort ()
public java.lang.String getProtocol ()
public java.lang.String getQuery ()
protocol:http prot:80 host:www.yahoo.ru path:/en/index.html file:/en/index.html?name=joe query:name=joe ref:first
ProtocolTester
import java.net.URL;
public class MainClass {
public static void main(String[] args) {
String host = "www.jexp.ru";
String file = "/index.html";
String[] schemes = { "http", "https", "ftp", "mailto", "telnet", "file", "ldap", "gopher",
"jdbc", "rmi", "jndi", "jar", "doc", "netdoc", "nfs", "verbatim", "finger", "daytime",
"systemresource" };
for (int i = 0; i < schemes.length; i++) {
try {
URL u = new URL(schemes[i], host, file);
System.out.println(schemes[i] + " is supported\r\n");
} catch (Exception ex) {
System.out.println(schemes[i] + " is not supported\r\n");
}
}
}
}
provides a simple interface for assembling GET URLs
public class URLBuilder {
private StringBuffer mBuffer;
private boolean mHasParameters;
public URLBuilder(String base) {
mBuffer = new StringBuffer(base);
mHasParameters = false;
}
public void addParameter(String name, String value) {
if (mHasParameters == false) {
mBuffer.append("?");
mHasParameters = true;
} else
mBuffer.append("&");
mBuffer.append(name);
mBuffer.append("=");
mBuffer.append(value);
}
public String toString() {
return mBuffer.toString();
}
}
Read from URL
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
public class MainClass {
public static void main(String[] args) throws Exception {
URL u = new URL("http://www.jexp.ru");
InputStream in = u.openStream();
in = new BufferedInputStream(in);
Reader r = new InputStreamReader(in);
int c;
while ((c = r.read()) != -1) {
System.out.print((char) c);
}
}
}
Reading A Web Resource: Opening a URL"s stream
You can use the URL class"s openStream method to read a Web resource.
public final java.io.InputStream openStream() throws java.io.IOException
Relative URL
import java.net.MalformedURLException;
import java.net.URL;
public class MainClass {
public static void main(String[] a) {
try {
URL base = new URL("http://www.jexp.ru/");
URL relative = new URL(base, "index.html");
System.out.println(relative);
} catch (MalformedURLException ex) {
;
}
}
}
http://www.jexp.ru/index.html
Resolve a relative URL
import java.net.URL;
public class Main {
public static void main(String[] argv) throws Exception {
URL relativeURL, baseURL;
baseURL = new URL("http://www.yourserver.ru/");
relativeURL = new URL(baseURL, "./a.htm");
System.out.println(relativeURL.toExternalForm());
}
}
Returns the anchor value of the given URL
public class Utils {
public static final String ANCHOR_CHAR = "#"; //$NON-NLS-1$
/**
* Returns the anchor value of the given URL.
*
* @param url
* URL
* @return anchor value, or null if none was defined
*/
public static String getAnchor(String url) {
if (url != null) {
int anchorPosition = url.indexOf(ANCHOR_CHAR);
if (anchorPosition >= 0) {
return url.substring(anchorPosition + 1);
}
}
return null;
}
}
Returns true if the URL represents a path, and false otherwise.
import java.io.File;
import java.net.URL;
/*
* JCommon : a free general purpose class library for the Java(tm) platform
*
*
* (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jcommon/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ------------
* IOUtils.java
* ------------
* (C)opyright 2002-2004, by Thomas Morgner and Contributors.
*
* Original Author: Thomas Morgner;
* Contributor(s): David Gilbert (for Object Refinery Limited);
*
* $Id: IOUtils.java,v 1.8 2009/01/22 08:34:58 taqua Exp $
*
* Changes
* -------
* 26-Jan-2003 : Initial version
* 23-Feb-2003 : Documentation
* 25-Feb-2003 : Fixed Checkstyle issues (DG);
* 29-Apr-2003 : Moved to jcommon
* 04-Jan-2004 : Fixed JDK 1.2.2 issues with createRelativeURL;
* added support for query strings within these urls (TM);
*/
/**
* The IOUtils provide some IO related helper methods.
*
* @author Thomas Morgner.
*/
public class Main {
/**
* Returns <code>true</code> if the URL represents a path, and
* <code>false</code> otherwise.
*
* @param baseURL the URL.
*
* @return A boolean.
*/
private boolean isPath(final URL baseURL) {
if (getPath(baseURL).endsWith("/")) {
return true;
}
else if (baseURL.getProtocol().equals("file")) {
final File f = new File(getPath(baseURL));
try {
if (f.isDirectory()) {
return true;
}
}
catch (SecurityException se) {
// ignored ...
}
}
return false;
}
/**
* Implements the JDK 1.3 method URL.getPath(). The path is defined
* as URL.getFile() minus the (optional) query.
*
* @param url the URL
* @return the path
*/
private String getPath (final URL url) {
final String file = url.getFile();
final int queryIndex = file.indexOf("?");
if (queryIndex == -1) {
return file;
}
return file.substring(0, queryIndex);
}
}
Save binary file from URL
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class MainClass {
public static void main(String args[]) throws Exception {
URL u = new URL("http://www.jexp.ru/binary.dat");
URLConnection uc = u.openConnection();
String contentType = uc.getContentType();
int contentLength = uc.getContentLength();
if (contentType.startsWith("text/") || contentLength == -1) {
throw new IOException("This is not a binary file.");
}
InputStream raw = uc.getInputStream();
InputStream in = new BufferedInputStream(raw);
byte[] data = new byte[contentLength];
int bytesRead = 0;
int offset = 0;
while (offset < contentLength) {
bytesRead = in.read(data, offset, data.length - offset);
if (bytesRead == -1)
break;
offset += bytesRead;
}
in.close();
if (offset != contentLength) {
throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes");
}
String filename = u.getFile().substring(filename.lastIndexOf("/") + 1);
FileOutputStream out = new FileOutputStream(filename);
out.write(data);
out.flush();
out.close();
}
}
URL Equality
import java.net.MalformedURLException;
import java.net.URL;
public class MainClass {
public static void main(String[] args) {
try {
URL ibiblio = new URL("http://www.google.ru/");
URL metalab = new URL("http://www.google.ca/");
if (ibiblio.equals(metalab)) {
System.out.println(ibiblio + " is the same as " + metalab);
} else {
System.out.println(ibiblio + " is not the same as " + metalab);
}
} catch (MalformedURLException ex) {
System.err.println(ex);
}
}
}
http://www.google.ru/ is not the same as http://www.google.ca/
URL Splitter
import java.net.URL;
public class MainClass {
public static void main(String args[]) throws Exception {
URL u = new URL("http://www.jexp.ru:80/index.html");
System.out.println("The URL is " + u);
System.out.println("The scheme is " + u.getProtocol());
System.out.println("The user info is " + u.getUserInfo());
String host = u.getHost();
if (host != null) {
int atSign = host.indexOf("@");
if (atSign != -1)
host = host.substring(atSign + 1);
System.out.println("The host is " + host);
} else {
System.out.println("The host is null.");
}
System.out.println("The port is " + u.getPort());
System.out.println("The path is " + u.getPath());
System.out.println("The ref is " + u.getRef());
System.out.println("The query string is " + u.getQuery());
}
}
The URL is http://www.jexp.ru:80/index.html The scheme is http The user info is null The host is www.jexp.ru The port is 80 The path is /index.html The ref is null The query string is null
Utility to convert File to URL.
/*
* JBoss DNA (http://www.jboss.org/dna)
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership. Some portions may be licensed
* to Red Hat, Inc. under one or more contributor license agreements.
* See the AUTHORS.txt file in the distribution for a full listing of
* individual contributors.
*
* JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
* is licensed to you under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* JBoss DNA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
public class FileMonitor {
/**
* Utility to convert {@link File} to {@link URL}.
*
* @param filePath the path of the file
* @return the {@link URL} representation of the file.
* @throws MalformedURLException
* @throws IllegalArgumentException if the file path is null, empty or blank
*/
public static URL convertFileToURL( String filePath ) throws MalformedURLException {
File file = new File(filePath.trim());
return file.toURI().toURL();
}
}