2010-04-15 56 views
2

如果我處理文件,如何創建文檔並寫入文檔?現在,我有完全刪除的文件,並用新的內容重新創建,如下圖所示:如何在eclipse中寫入文件?

IFile file = getFile(); 
file.delete(); 
file.create(input, false, null); 

編輯:這是一個Eclipse插件,而不是一個普通的Java程序。

回答

0

找到答案在這裏:http://old.nabble.com/how-to-get-the-IDocument-of-an-ITextFileBuffer-created-from-an-IFile--td19222160.html

不得不修改了一點,以滿足我的需要:

FileEditorInput editorInput = new FileEditorInput(file); 
IWorkbench wb = PlatformUI.getWorkbench(); 
IWorkbenchPage page = wb.getActiveWorkbenchWindow().getActivePage(); 
IEditorDescriptor desc = wb.getEditorRegistry().getDefaultEditor(file.getName()); 
IEditorPart editor = (IEditorPart)page.openEditor(editorInput, desc.getId()); 
ITextEditor textEditor = (ITextEditor) editor.getAdapter(ITextEditor.class); 
IDocumentProvider documentProvider = textEditor.getDocumentProvider(); 
IDocument document = documentProvider.getDocument(editorInput); 
document.replace(position, 0, content); 
1

發生這種情況是因爲您正嘗試讀取不存在的文件。因此,通過獲取文件並關閉它,然後創建文件。

+0

很好的答案,但如何在特定位置寫字? – fastcodejava 2010-04-19 07:14:43

+0

我想「輸入」是文件名。所以說我有這個文件在 的C盤(假設你正在運行的窗口)。我還假設「輸入」是一個字符串。然後按照以下步驟操作 String n =「C:/」+ input; 該字符串將最終看起來像這樣:C:\ file_name – flopex 2010-04-19 15:24:58

1

的IFile接口似乎有一些方法,這樣可以讓你寫一些內容:

/** 
* Appends the entire contents of the given stream to this file. 
* ... 
*/ 
public void appendContents(InputStream source, boolean force, boolean keepHistory, IProgressMonitor monitor) throws CoreException; 
+0

好的答案,但如何在特定位置寫入? – fastcodejava 2010-04-19 17:22:28