2016-12-19 147 views
0

我正在使用Java,我需要將兩個.rtf文件以其原始格式(包括兩個rtf文件)一起追加,連續編譯,合併或添加,無論哪個是正確的術語,放入一個rtf文件。每個rtf文件都是一個頁面,所以我需要從兩個文件中創建一個兩頁的rtf文件。合併RTF文件?

我還需要在新組合的rtf文件中創建兩個文件之間的分頁符。我去了MS的話,並能夠將兩個rtf文件結合在一起,但是這只是創建了一個沒有分頁符的長rtf文件。

我有一個代碼,但它只是將文件複製到相同的方式另一個文件,但我需要調整出這個代碼的幫助,所以我可以兩個文件複製到一個文件

FileInputStream file = new FileInputStream("old.rtf"); 
    FileOutputStream out = new FileOutputStream("new.rtf"); 

    byte[] buffer = new byte[1024]; 

    int count; 

    while ((count= file.read(buffer)) > 0) 
     out.write(buffer, 0, count); 

怎麼辦我在FileInputStream文件的頂部添加另一個FileInputStream對象,FileOutputStream輸出,文件和對象之間有分頁符?

我完全卡住了。我能夠將兩個rtf文件與幫助相結合,但無法將兩個rtf文件的原始格式保留爲新格式。

我試過:

FileInputStream file = new FileInputStream("old.rtf"); 
    FileOutputStream out = new FileOutputStream("new.rtf", true); 

    byte[] buffer = new byte[1024]; 

    int count; 
    while ((count= file.read(buffer)) > 0) 
    out.write(buffer, 0, count); 

FileOutputStream中(文件文件,布爾追加),其中old.rtf是假設追加到new.rtf,但是當我做吧,old.rtf只是寫入new.rtf。

我在做什麼錯?

回答

0

當您打開要添加到的文件時,請使用FileOutputStream(File file, boolean append)並將append設置爲true,然後您可以將其添加到新文件中,而不是將其寫入。

FileInputStream file = new FileInputStream("old.rtf"); 
FileOutputStream out = new FileOutputStream("new.rtf", true); 

byte[] buffer = new byte[1024]; 

int count; 

while ((count= file.read(buffer)) > 0) 
    out.write(buffer, 0, count); 

這將追加到old.rtfnew.rtf

你也可以這樣做:

FileInputStream file = new FileInputStream("old1.rtf"); 
FileOutputStream out = new FileOutputStream("new.rtf"); 

byte[] buffer = new byte[1024]; 

int count; 

while ((count= file.read(buffer)) > 0) 
    out.write(buffer, 0, count); 

file.close(); 

file = new FileOutputStream("old2.rtf"); 
while ((count= file.read(buffer)) > 0) 
    out.write(buffer, 0, count); 

這將串聯old1.rtfold2.rtf到新文件new.rtf

+0

有什麼方法可以闡述答案。這有點合理,但仍然很失敗。謝謝 – user2852918

+0

Will Hartung,我真的很感謝你的迴應,並且知道它的正確性,但我無法理解它。我試圖把它放進去,並不適合我。我究竟做錯了什麼??我對這個太新了,只是沒有得到它。 – user2852918