2016-09-13 43 views
1


雖然我一直在尋找這些論壇很久,但我終於需要一些幫助; 我試過這個;如何在vaadin中顯示文本文件

FileResource file = new FileResource(new File("https://stackoverflow.com/a/d/r/e/s/s/file")); 
TextArea text = new TextArea(); 
text.setValue(file); 

這個;

FileResource file = new FileResource(new File("https://stackoverflow.com/a/d/r/e/s/s/file")); 
TextArea text = new TextArea(); 
text.setValue(file.toString()); 

而;

FileResource file = new FileResource(new File("https://stackoverflow.com/a/d/r/e/s/s/file")); 
TextArea text = new TextArea(); 
text.setValue(file.getAbosoluteFile().toString()); 

和其他的是要大顯示;

如何顯示文件

+2

可能重複[如何從文件內容創建Java字符串?](http://stackoverflow.com/questions/326390/how-do-i-create-a-java-string-from一個文件的內容) – shmosel

+0

我不認爲這是重複的,因爲這個問題是關於填充Vaadin組件而不僅僅是一個字符串。 –

+0

嗨@WillPierlot如果任何答案已解決您的問題,請考慮通過點擊複選標記來接受它。這向更廣泛的社區表明,您已經找到了解決方案,併爲答覆者和您自己提供了一些聲譽。沒有義務這樣做。 –

回答

3

最簡單的方法是使用TextFileProperty

TextArea text = new TextArea(new TextFileProperty(new File("https://stackoverflow.com/a/d/r/e/s/s/file"))); 

或更長的形式:

TextArea text = new TextArea(); 
text.setPropertyDataSource(new TextFileProperty(new File("https://stackoverflow.com/a/d/r/e/s/s/file"))); 

什麼這一段代碼做它是否將您的Field TextArea綁定到屬性。這是Vaadin的數據綁定機制。屬性和字段自動同步。

如果您只想顯示文件而不進行編輯,請考慮使用Vaadin標籤而不是TextArea。

1
final TextArea textField = new TextArea(); 
textField.setSizeFull(); 
this.addComponent(textField); 
try { 
    final File file = new File("/path/to/file"); 
    final String fileAsString = FileUtils.readFileToString(file); 
    textField.setValue(fileAsString); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

您將需要有來自Apache的百科全書提供的IO組件能夠導入文件實用程序

+2

您可以直接添加相關的軟件包名稱,也可以添加爲'import'語句。 – Robert

0

使用Java標準庫+ java的8流

TextArea text = new TextArea(); 
String value = Files.readAllLines(Paths.get(file)).stream().collect(Collectors.joining()) 
text.setValue(value); 

在Java 7中,您可以使用readAllLines函數迭代生成的List,如果文件的大小非常大,請遵循differen牛逼的做法,因爲這是在這裏解釋了一個http://www.baeldung.com/java-read-lines-large-file