开发者

How do I write to a file in eclipse?

If I have handle to file how do I create a document and write to it? Right now, I am having to delete the file completely and recreate with new content as shown below :

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

EDIT : This is in an eclipse plugin, not a regular j开发者_运维百科ava program.


This happens because you are trying to read a file that doesn't exist. So by getting the file and closing it then you actually create the file.


IFile interface seems to have some methods which would allow you to write some content:

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


Found the answer here : http://old.nabble.com/how-to-get-the-IDocument-of-an-ITextFileBuffer-created-from-an-IFile--td19222160.html

Had to modify a little to suit my need:

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜