2012-07-29 69 views
2

我有一個問題給大家。我追求速度,而且我需要使用這種方法,所以這種方法效率越高越好。Java - 從網站加載文本的最有效方式?

我的代碼:

private void method(final String name) { 
    final URL url = new URL("http://www.somewebsite.com/blah.php?name=" + name); 
    final BufferedReader in = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream())); 
    final String totalText = in.readLine(); 
    in.close(); 
    //other stuff using the totalText variable 
} 

這種方法工作,但我問是否有這個工作一個有效的方式。

重要事項關於我讀的代碼:

  • 從網站上整個源代碼是唯一一個長。
  • 還有沒有帶有網站代碼的HTML標籤。這全是原始文字。
+0

我不知道......會'totalText = in.readLine();'工作?然後,我將刪除'inputLine'變量和'while'循環? – Confiqure 2012-07-29 18:43:31

+0

如果您確定它始終是1行,是的。但不應該加快這一點 – 2012-07-29 18:45:45

+0

大家:我修改了我的代碼。 – Confiqure 2012-07-29 18:46:27

回答

2

如果代碼一行,因爲你已經改變了你的問題,然後執行以下操作... 只供InputStreamScanner

final URL url = new URL("http://www.somewebsite.com/blah.php?name=" + name); 
InputStream i = url.openStream(); 
Scanner scan = new Scanner(i); 
final String totalText = scan.nextLine(); 

2.如果多張行的話,我會建議你不創建一個String對象的每時間,導致對堆創建對象是昂貴的。

這些2下面的行會在堆上創建很多String對象

((inputLine = in.readLine()) != null)

totalText += inputLine;

使用StringBuilder易變,並在結束其分配到使用toString()方法的字符串參考。

如:

StringBuilder totalText; 
    String ftotal; 

    while ((inputLine = in.readLine()) != null) { 
    totalText.append(inputLine); 
} 


    ftotal = totalText.toString(); 
+0

從他的問題:整個網站的源代碼只有一行長 – 2012-07-29 18:38:56

+0

@OskarKjellin這是正確的。 – Confiqure 2012-07-29 18:40:58

+0

@ JavaCoder-1337你能否澄清誰是正確的.....? – 2012-07-29 18:44:17

相關問題