This demo is premised on creating a new HelloWorld.txt under the WebApps Example folder of the Tomcat server. and writes a write content
Package Mynetdemo;
Import static org.junit.assert.*;
Import Java.io.File;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import java.net.MalformedURLException;
Import Java.net.URL;
Import java.net.URLConnection;
Import Org.junit.Test; public class Testurl {//URL Uniform Resource Locator, a URL object that corresponds to a resource on the Internet/can invoke its corresponding method through the URL object to read this resource to public static void main (string[]
args) {//Create a URL object URL url = null;
How to read the resources in the server side: OpenStream () InputStream iStream = null;
int Len;
try {url = new URL ("Http://127.0.0.1:8080/examples/HelloWorld.txt?a=b");
* * * SYSTEM.OUT.PRINTLN (Url.getprotocol ());
* SYSTEM.OUT.PRINTLN (Url.gethost ());
* SYSTEM.OUT.PRINTLN (Url.getport ());
* SYSTEM.OUT.PRINTLN (Url.getpath ()); * SYSTEM.OUT.PRINTLN (Url.getfile ());//url filename * SYSTEM.OUT.PRINTLN (Url.getref ());//Get the relative position of the URL in the file * System.out.prin TLN (Url.getquery ()//Get URL query name * * IStream = Url.openstream ();
Byte[] B = new BYTE[20];
while (len = Istream.read (b))!=-1) {string string = new String (b, 0, Len);
System.out.println (string);
} catch (Malformedurlexception E1) {//TODO auto-generated catch block E1.printstacktrace ();
catch (IOException E1) {//TODO auto-generated catch block E1.printstacktrace ();
finally {if (IStream!= null) {try {istream.close ();
catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
To read in the resource and want to write out resources,: urlconnection inputstream is = null;
FileOutputStream fos = null;
try {url = new URL ("Http://127.0.0.1:8080/examples/HelloWorld.txt?a=b");
URLConnection connection = Url.openconnection ();
is = Connection.getinputstream ();
FOS = new FileOutputStream (New File ("Out1.txt"));
Byte[] B1 = new BYTE[20];
int len1; while ((Len1 = Is.read (B1))!=-1) {Fos.write (B1, 0, leN1);
} catch (FileNotFoundException E1) {//TODO auto-generated catch block E1.printstacktrace ();
catch (IOException E1) {//TODO auto-generated catch block E1.printstacktrace ();
finally {if (FOS!= null) {try {fos.close ();
catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
} if (is!= null) {try {is.close ();
catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
}
}
}
}
}