Reading from URL into String

Question:
What is the maximum size of a string array I can have in my applet?I am trying to store some stock prices in a string array after reading themfrom a URL connection, but I get an applet exception. What is going wrong?Any suggestions?

Answer:
I suspect you’re trying to read the contents of the URL usingURLConnection.getContent() and that this is not working for you.Netscape’s implementation of getContent() is known to have bugswhen it’s dealing with simple text files. A better way to read the datainto your applet is to use InputStreams.

For example, if your stock data were stored in a text file called”stock.txt” on the Web server and you wanted your applet to read thecontents of “stock.txt” into a string using a URL, you would do thefollowing:

       String inputLine;       String stockData = “”;       URL stockURL = new URL(getDocumentBase(), “stock.txt”));       DataInputStream s = new DataInputStream(stockURL.openStream());       while ((inputLine = s.readLine()) != null) {               stockData = stockData + inputLine;       }       s.close(); 
This will read the contents of “stock.txt” into a single Stringobject and allocate memory for it as needed. The String willgrow to accommodate the amount of data in the data file. You canthen use StringTokenizer to read the data out of the String andparse it as you see fit.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: