Ido
Ido

Reputation: 255

create a new java file in eclipse plugin

I'm creating an eclipse plug-in. I have a string with java code, and I want to save this code to a project. I used the IFile to create my file. Is there another way that is better for saving java code?

Ido

Upvotes: 2

Views: 3498

Answers (4)

VonC
VonC

Reputation: 1327324

Note that Eclipse 4.33 (Q3 2024) does come with:

Enhanced IFile API for create/read/write

The org.eclipse.core.resources plug-in defines the following new methods:

  • IFile.create(byte[], boolean, boolean, IProgressMonitor)
  • IFile.create(byte[], int, IProgressMonitor)
  • IFile.write(byte[], boolean, boolean, boolean, IProgressMonitor)
  • IFile.setContents(byte[], boolean, boolean, IProgressMonitor)
  • IFile.setContents(byte[], int, IProgressMonitor)
  • IFile.readAllBytes()
  • IFile.readNBytes(int)
  • IFile.readAllChars()
  • IFile.readString()

These methods are for convenience and are optimized for performance, handling small files that do not require streaming.

Upvotes: 0

dplass
dplass

Reputation: 1473

You could write a nature and builder that saves the text as a file with the ".java" extension, and the JDT will pick it up as long as build automatically is turned on.

Upvotes: 0

iain
iain

Reputation: 10928

I followed the example from the book Contributing to Eclipse.

Download the sample code from here http://www.informit.com/store/product.aspx?isbn=0321205758

It is in a class called TestProject.

Basically it creates a org.eclipse.jdt.core.IJavaProject from the IProject. And creates a org.eclipse.jdt.core.ICompilationUnit from a org.eclipse.jdt.core.IPackageFragment

IPackageFragment pack = sourceFolder.createPackageFragment(packageName, false, null);
StringBuffer buf = new StringBuffer();
buf.append("package " + pack.getElementName() + ";\n");
buf.append("\n");
buf.append(source);
ICompilationUnit cu = pack.createCompilationUnit(cuName, buf.toString(), false, null);

By the way this is an excellent book and shows how to unit test part of you plugin that you don't think are testable.

Upvotes: 0

James E. Ervin
James E. Ervin

Reputation: 161

I am thinking about this one. Using IFile and then allowing the JDT to discover it will work just fine, it definitely has the advantage of simplicity. That is what the org.eclipse.core.resources API is designed to allow. If you want to know more take a look at JavaCore which is in the org.eclipse.jdt.core bundle. What you might be looking for would be after creating your IFile to invoke JavaCore.create( file ) where file is your newly created IFile instance.

Upvotes: 0

Related Questions