tags:

views:

135

answers:

3

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.

+1  A: 

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.

flopex
Good answer, but how to I write at a specific location?
fastcodejava
I imagine that "input" is the file name. So say I have that file inthe C drive (Assuming your running windows). I also assume that "input" is a String. Then do as follow; String n = "C:/"+input;The string will end up looking like this: C:\file_name
flopex
+1  A: 

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;
Grzegorz Oledzki
Good answer, but how to I write at a specific location?
fastcodejava
+1  A: 

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