2012-09-24 55 views
9

可能重複:
How to create a Java String from the contents of a fileJava:如何將文件對象轉換爲Java中的字符串對象?

我有我想要使用提取信息的HTML文件。爲此,我正在使用Jsoup。 現在爲了使用Jsoup,我需要將html文件轉換爲字符串。我怎樣才能做到這一點?

File myhtml = new File("D:\\path\\report.html")'; 

現在,我想要一個包含html文件內的內容的String對象。

final String EoL = System.getProperty("line.separator"); 
List<String> lines = Files.readAllLines(Paths.get(fileName), 
     Charset.defaultCharset()); 

StringBuilder sb = new StringBuilder(); 
for (String line : lines) { 
    sb.append(line).append(EoL); 
} 
final String content = sb.toString(); 

但是,它並havea一些輕微的警告(如處理不適合到內存中的文件):

+3

檢查:http://stackoverflow.com/questions/326390/how-to-create-a-java-string-from-the-contents-of-a-file –

+0

通過閱讀文件字符字符並將每個字符放在一個StringBuffer中。完成後向StringBuffer詢問字符串。 –

+2

檢查jsoup api。它具有采用文件的'parse'方法。您不需要手動讀取文件內容。 –

回答

23

我用apache common IO讀取文本文件合併成一個字符串

String str = FileUtils.readFileToString(file); 

簡單,「乾淨」。你甚至可以毫不費力地設置文本文件的編碼。

String str = FileUtils.readFileToString(file, "UTF-8"); 
+0

你會如何做相反的... readStringToFile –

+2

writeStringToFile? – gigadot

+0

附件鏈接已過期,您能否發佈最新的網址? –

8

使用Java 7,它是那樣簡單。

我建議在官方Java教程中看看corresponding section(如果您有先前的Java,也是這種情況)。

正如其他人指出的,你可能會發現sime第三方庫很有用(如Apache公用I/O或番石榴)。

0

爲什麼你只是不按行讀取文件並將其添加到StringBuffer?

到達文件結尾後,您可以從StringBuffer中獲取字符串。

0

可以的myhtml所有內容複製到String如下:

Scanner myScanner = null; 
try 
{ 
    myScanner = new Scanner(myhtml); 
    String contents = myScanner.useDelimiter("\\Z").next(); 
} 
finally 
{ 
    if(myScanner != null) 
    { 
     myScanner.close(); 
    } 
} 

Ofcourse,你可以添加一個catch塊妥善處理異常。

9

使用圖書館像GuavaCommons/IO。他們有在線方法。

番石榴:

Files.toString(file, charset); 

共享/ IO:

FileUtils.readFileToString(file, charset); 

沒有這樣的庫,我會寫一個輔助方法,像這樣:

public String readFile(File file, Charset charset) throws IOException { 
    return new String(Files.readAllBytes(file.toPath()), charset); 
} 
2

Reading新文件使用文件輸入流並將文件內容附加到字符串。

import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 

public class CopyOffileInputStream { 

    public static void main(String[] args) { 

     //File file = new File("./store/robots.txt"); 
     File file = new File("swingloggingsscce.log"); 

     FileInputStream fis = null; 
     String str = ""; 

     try { 
      fis = new FileInputStream(file); 
      int content; 
      while ((content = fis.read()) != -1) { 
       // convert to char and display it 
       str += (char) content; 
      } 

      System.out.println("After reading file"); 
      System.out.println(str); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (fis != null) 
        fis.close(); 
      } catch (IOException ex) { 
       ex.printStackTrace(); 
      } 
     } 
    } 
} 
相關問題