eclipse中編程建立一個java項目

來源:互聯網
上載者:User

步驟:
1. 建立一個org.eclipse.core.resources.IProject
2. 給該project設定description,也就是產生.project檔案
注意:a、JavaCore.NATURE_ID = "org.eclipse.jdt.core.javanature"表示是個java project
b、在將description置入project時,保證project是存在的並且開啟中。
3. 將org.eclipse.core.resources.IProject轉換為java project
IJavaProject javaProject=JavaCore.create(project);
4. 取得eclipse的jre路徑和當前project的路徑,設定原始碼的存放目錄以及*.class檔案的存放目錄
這塊產生的是.classPath檔案中的內容
5. 將一個字串編譯為java檔案和對應的.class檔案

example:
package org.wliu.sample.createnewjavaproject.actions;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;

/**
* Our sample action implements workbench action delegate.
* The action proxy will be created by the workbench and
* shown in the UI. When the user tries to use the action,
* this delegate will be created and execution will be
* delegated to it.
* @see IWorkbenchWindowActionDelegate
*/
public class SampleAction implements IWorkbenchWindowActionDelegate {
private IWorkbenchWindow window;
/**
* The constructor.
*/
public SampleAction() {
}

/**
* The action has been activated. The argument of the
* method represents the 'real' action sitting
* in the workbench UI.
* @see IWorkbenchWindowActionDelegate#run
*/
public void run(IAction action) {
MessageDialog.openInformation(
window.getShell(),
"CreateNewJavaProject Plug-in",
"Hello, Eclipse world");
// create the resource project
IWorkspaceRoot root=ResourcesPlugin.getWorkspace().getRoot();
org.eclipse.core.resources.IProject project = root.getProject("wliu");
IJavaProject javaProject =null;
if(!project.exists()){
IProjectDescription prjDesc=root.getWorkspace().newProjectDescription(project.getName());
String[] oldNatureIds=prjDesc.getNatureIds();
String[] newNatureIds = new String[oldNatureIds.length+1];
System.arraycopy(oldNatureIds, 0, newNatureIds, 0, oldNatureIds.length);
newNatureIds[oldNatureIds.length]=JavaCore.NATURE_ID;// define this is a java project
prjDesc.setNatureIds(newNatureIds);
try {
project.create(new NullProgressMonitor());
project.open(IResource.BACKGROUND_REFRESH, new SubProgressMonitor(new NullProgressMonitor(), 1000));
project.setDescription(prjDesc, new NullProgressMonitor());
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}else{
try{
IProjectDescription prjDesc=project.getDescription();
String[] oldNatureIds=prjDesc.getNatureIds();
String[] newNatureIds = new String[oldNatureIds.length+1];
System.arraycopy(oldNatureIds, 0, newNatureIds, 0, oldNatureIds.length);
newNatureIds[oldNatureIds.length]=JavaCore.NATURE_ID;// define this is a java project
prjDesc.setNatureIds(newNatureIds);
project.open(IResource.BACKGROUND_REFRESH, new SubProgressMonitor(new NullProgressMonitor(), 1000));
project.setDescription(prjDesc, new NullProgressMonitor());
}catch(CoreException e){
e.printStackTrace();

}
}
javaProject=JavaCore.create(project);
// create the classpath entries

// get the platform's jre classpath
IClasspathEntry[] jreClasspaths=PreferenceConstants.getDefaultJRELibrary();
// get the project existing classpath
IClasspathEntry[] oldClasspathEntries = null;
try {
oldClasspathEntries = javaProject.getRawClasspath();
} catch (JavaModelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Set<IClasspathEntry> newClasspathEntries = new HashSet<IClasspathEntry>();
newClasspathEntries.addAll(Arrays.asList(jreClasspaths));
newClasspathEntries.addAll(Arrays.asList(oldClasspathEntries));
//        try {
//           
javaProject.setRawClasspath(newClasspathEntries.toArray(new
IClasspathEntry[newClasspathEntries.size()]), new
NullProgressMonitor());
//        } catch (JavaModelException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }

// create the output location
IFolder binFolder=javaProject.getProject().getFolder("bin");
try {
if(!binFolder.exists()){
binFolder.create(true, true, new NullProgressMonitor());
}
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
javaProject.setOutputLocation(binFolder.getFullPath(), new NullProgressMonitor());
} catch (JavaModelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

// create the source folder
IFolder srcFolder = javaProject.getProject().getFolder("src");
if(!srcFolder.exists()){
try {
srcFolder.create(true, true, null);
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}           
}

// add the src classpath entry to the .classpath file
IClasspathEntry classpathEntry=JavaCore.newSourceEntry(srcFolder.getFullPath());
newClasspathEntries.add(classpathEntry);
IClasspathEntry removeEntry = JavaCore.newSourceEntry(new Path("/"+project.getName()));
if(newClasspathEntries.contains(removeEntry)){
newClasspathEntries.remove(removeEntry);
}
try {
javaProject.setRawClasspath(newClasspathEntries.toArray(new
IClasspathEntry[newClasspathEntries.size()]), new
NullProgressMonitor());
} catch (JavaModelException e) {
// TODO Auto-generated catch block
System.err.println("error");
e.printStackTrace();
}
System.out.println("OK");

try {
IPackageFragmentRoot fileRoot = javaProject.findPackageFragmentRoot(new Path("/"+project.getName()+"/src"));

IPackageFragment packageFragment=fileRoot.createPackageFragment("org.talend.sample", true, new NullProgressMonitor());

String strJava = "package org.talend.sample;public class Test{public static void main(String[] args){"+
"System.out.println(/"OK/");}}";
packageFragment.createCompilationUnit("Test.java", strJava, true, new NullProgressMonitor());

}catch(JavaModelException e){

}

}

/**
* Selection in the workbench has been changed. We
* can change the state of the 'real' action here
* if we want, but this can only happen after
* the delegate has been created.
* @see IWorkbenchWindowActionDelegate#selectionChanged
*/
public void selectionChanged(IAction action, ISelection selection) {
}

/**
* We can use this method to dispose of any system
* resources we previously allocated.
* @see IWorkbenchWindowActionDelegate#dispose
*/
public void dispose() {
}

/**
* We will cache window object in order to
* be able to provide parent shell for the message dialog.
* @see IWorkbenchWindowActionDelegate#init
*/
public void init(IWorkbenchWindow window) {
this.window = window;
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.