2015-03-03 25 views
0

我在一個類中這兩種方法:設置一個PrintStream對象到一個FileWriter

public SimpleTreeWriterImpl(PrintStream out) { 
    outStream = out; 
} 

@Override 
public void setDestination(PrintStream output) { 
    outStream = output; 

} 

,但現在我需要設置outStream打印到一個文本文件,但是我不知道如何做到這一點,我嘗試將File對象傳遞給setDestination()方法,但它表示這些是不兼容的類型。

如何將目的地設置爲特定的文本文件?

+0

只是爲了確認,當你說「我試圖解析文件」 - 你的意思是你試圖通過***一***將'File'對象放入'setDestination()'方法中? – 2015-03-03 13:16:03

+0

是的,我的意思是 – Onwardplum 2015-03-03 13:35:28

+0

確定 - 編輯你的問題 - 你也可以添加更正等[使用編輯鏈接](http://stackoverflow.com/posts/28832155/edit) – 2015-03-03 13:39:32

回答

0

試試這個:

PrintStream writetoEngineer = new PrintStream(new FileOutputStream("Engineer.txt", true)); 
+0

但我需要設置目的地爲一個特定的文件 – Onwardplum 2015-03-03 12:51:12

+0

我認爲這個答案可以使用一個上下文 - 我認爲@joaomarcos建議你建立一個基於'FileOutputStream'對象的'PrintStream'對象,該對象可以與任何你喜歡的文件相關聯(在他的例子''「 Engineer.txt「')。然後你可以將這個對象(在他的例子'writetoEngineer'中)傳遞給你現有的'setDesination()'方法,它應該都可以工作。 – 2015-03-03 13:15:00

0

錯誤是告訴你,File不是PrintStream。您的setDestination()方法將僅採用PrintStream類型的對象。所以,你需要實例化一個PrintStream對象(或PrintStream子類)

PrintStream api來看,我們看到可以construct a Prinstream directly from a String filename。這是(至少)的Java版本6,7和8。所以,你需要的是調用的方法setDestination如下情況:

setDestination(new PrintStream("path/to/your/output/file.txt")); 

注意 - Prinstream也有constructor that takes a File object,因此,如果您正在處理的File對象,而不是String文件名 - 使用下面的:

setDestination(new PrintStream(yourFileObject)); 
相關問題