如何清除缓存JAVA应用程序

时间:2012-05-16 07:10:11

标签: java http

我使用java.net库创建了一个应用程序来捕获网页打开的时间..示例代码

 HttpURLConnection conn = (HttpURLConnection)url.openConnection();
 for(int i=0; i<20; i++ )
  {
   conn.disconnect();
   conn.connect();
   long starTime = System.currentTimeMillis();
   JEditorPane editorPane = new JEditorPane();
   editorPane.setPage(new URL());
   long elasedTime = System.currentTimeMillis() - starTime;
   System.out.println(elasedTime);
  }

但是我遇到了问题,缓存!! 如果我反复打开网页,那么在某些情况下它会显示时间= 0毫米......这当然是不可能的,请有人帮我这个!!

4 个答案:

答案 0 :(得分:2)

继承自setUseCaches()

URLConnection应提供所需内容:

public void setUseCaches(boolean usecaches)

Sets the value of the useCaches field of this URLConnection to
the specified value. 

Some protocols do caching of documents. Occasionally, it is important to be
able to "tunnel through" and ignore the caches (e.g., the "reload" button in
a browser). If the UseCaches flag on a connection is true, the connection is
allowed to use whatever caches it can. If false, caches are to be ignored.
The default value comes from DefaultUseCaches, which defaults to true. 

必须在connect()之前调用。

答案 1 :(得分:1)

您可以通过设置conn.setUseCaches(false)来选择不使用任何现有缓存。这可能会提高计算的准确性。

答案 2 :(得分:0)

您可以在URLConnection(或HttpURLConnection)中停用缓存。

答案 3 :(得分:0)

rahul,你的计划有一个很大的错误。您的程序没有给出预期的结果,因为您没有正确编写,具体来说,您的程序没有测量网页打开所花费的时间。

试试这段代码 - &gt;

HttpURLConnection conn = (HttpURLConnection)url.openConnection();
 for(int i=0; i<20; i++ )
  {
   long starTime = System.currentTimeMillis();       
   conn.connect();

   JEditorPane editorPane = new JEditorPane();
   editorPane.setPage(new URL());

   long elasedTime = System.currentTimeMillis() - starTime;
   System.out.println(elasedTime);

   conn.disconnect();
  }

奇怪,没有人会注意到你的程序中的错误。