Thank the author: Wuhan University School of Communication and Information Ding Bo Tao ---- we know, for security reasons, Applet is not allowed to operate on the document in the Java Applet, not only allowed to write files, but is not allowed to read files. Although we use the statement Java that uses the file operation when we prepare the applet, you can run normally when you debug in the development tool (such as cafe), but when we run this applet in your browser, the browser will report an error. But sometimes we must read the contents of the file, such as to display the .txt file content in the server in the applet, is there no way?
---- Do not! There is a way. The decision is that we don't want to process files on these servers as normal files, but use them as network resources to get their content. There are two classes that can be used to obtain network resources in Java, one is the URL class, the other is the URLConnection class. Both classes provide methods of reading resource information in a word stream, and can be judged for the type of resource information to make corresponding processing. The difference is that the information available by the URLConnection class is much more than the URL class. In addition to obtaining resource data, there can also provide resources for resource length, resource transmission time, new update time, resource coding, title of resource, and other information. .
---- The following is a common method of two classes.
URL class: • URL (String, String, InT, String) Construction Method, create a URL object, URL (String, String, String) constructor containing protocol type, host name, port number, and path, create a type of protocol type The URL object of the host name and path, where the port number is the default value · URL (String) constructor, creates a URL object, the parameter combines the protocol, hostname, port number, and paths · URL (URL, STRING) constructor Create a new URL object with the relative path based on a given URL object · Object getContent () retrieve the URL content information, and return to the object · InputStream OpenStream () Returns a input stream from the resource · URLConnection OpenConnection () Generates a URLConnection object
URLConnection class: · Protected URLConnection (URL) Construction Method, create a URLConnection class for specifying the URL object · Object getContent () Returns the content of the URL object · InputStream getInputStream () Get the byte stream read from the object · protected Static String GuessContentTypefromstream (InputStream IS) is speculated according to the input stream
---- The .txt file content on the server is described below to illustrate how to read the file in the applet. Set the server's IP address of 202.114.1.16, the path to the .txt file is /File/Sample.txt. The following is the source code for the Applet reads the application.txt content.
//getfile.html