How do I write a file in eclipse?
If I have a file descriptor, how do I create a document and write to it? Right now I need to completely delete the file and create new content as shown below:
IFile file = getFile();
file.delete();
file.create(input, false, null);
EDIT : This is an eclipse plugin, not a regular Java program.
+2
a source to share
3 answers
Found the answer here: http://old.nabble.com/how-to-get-the-IDocument-of-an-ITextFileBuffer-created-from-an-IFile--td19222160.html
Had to change 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
a source to share
The IFile interface seems to have some methods that will 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;
+1
a source to share