开发者

Reading a remote xml file

I want to read a xml file that is presnt on a remote location.I use the following code

URL url = new URL(myurl);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
String strOutput = ""开发者_开发问答;
System.out.println("start now");
//my code hangs after  priting start now            
while ((inputLine = in.readLine()) != null) {
       strOutput = strOutput + inputLine;
}

//contol doesnot reach here sometimes
in.close();

Is this a good way to read a remote file.What is the network is slow?Please suggest


The comments have already indicated that there are some poor practices. I'll attempt to list what could be the cause of the poor performance:

  • Using readLine(). You are assuming that the XML file contains several lines, each terminated by either \r\n, \r or \n. This need not be the case, resulting the scenario where readLine() will take quite some time to complete.
  • Concatenating String objects. Strings are immutable in Java. Concatenating Strings will create a new String object, and this can become expensive if the size of the resulting string is quite large. If your document's ranges from a few bytes to kilobytes, this might not be an issue, but if it runs into megabytes, you are asking for trouble. Use StringBuilder or StringBuffer instead.
  • Assumptions on network performance. It might be better to fetch the file and parse it, instead of opening a connection, buffering it's contents and then parsing it. The network might simply not be capable of responding to your requests to read the file in a timely manner. By pre-fetching the file, you avoid hitting the network on every readLine() that will require reading beyond the buffered contents.


Why don't you consider using JAXB or other sophesticated XML readers they are optimized in reading XML files.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜