2011-10-05 54 views
0

可能重複:
How to create a Java String from the contents of a file加載文本到一個單一的字符串

我卡與加載整個文件(這是一個.html文件)的問題單串。

我試圖打印<body></body>之間的內容。然而;當我運行我的代碼時,它不能寫入輸入文件中的任何內容。我相信問題是我的第一行沒有<body></body>標記,這意味着indexOf()方法將返回-1,因此無法實現整個問題。有人告訴我應該加載整個.html包含很多行到一個單一的字符串,我相信他意味着加載在一行。我不知道該怎麼做...

這裏是我的代碼:

PrintWriter pr; 
try{ 
    c = new Scanner(f); 
pr = new PrintWriter(new FileOutputStream(o)); 
while (c.hasNextLine()){ 
    String text = c.nextLine(); 
    String index = "<body>"; 
    String index2 = "</body>"; 
    int i1 = text.indexOf(index); 
    int i2 = text.indexOf(index2); 
    text = text.substring(i1+6,i2); 
    System.out.println("here it is"); 
    pr.println(text); 
    System.out.println("you did !!!"); 
    pr.flush();} 
}catch(Exception e){} 

}

+0

謝謝。但實際上我不知道如何使用Buffer()方法.. – leohu

+0

你不能剪切和粘貼該代碼,看看它是否得到你一個字符串? – duffymo

+0

在這些解決方案中有很多未知的方法和類..對不起 – leohu

回答

0

確定。這裏有一個小樣本來幫助你開始。

這將工作將一個簡單的HTML頁面。
但對於複雜的頁面(嵌入CSS等),你將不得不計算如何找到正文的開始/結束。

FileInputStream fin = new FileInputStream("theFile.html");  
byte[] data = new byte[fin.available()];  
fin.read(data); 
String htmlFile = new String(data); 
int start = htmlFile.indexOf("<body>"); 
if(start != -1){ 
    int end = html.indexOf("</body"); 
    if(end != -1){ 

    System.out.println("Body is: html.substring(start + 6, end)); 
    } 
} 
相關問題