fastcodejava
fastcodejava

Reputation: 41097

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 java program.

Upvotes: 2

Views: 3027

Answers (3)

fastcodejava
fastcodejava

Reputation: 41097

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

Upvotes: 0

Grzegorz Oledzki
Grzegorz Oledzki

Reputation: 24261

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;

Upvotes: 1

flopex
flopex

Reputation: 454

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.

Upvotes: 1

Related Questions