在Eclipse运行时实例工作区中保存文件

时间:2015-02-27 15:46:21

标签: java eclipse eclipse-plugin resources

我有一个插件项目和自定义命令,通过单击右键单击获取文件。我的算法采用docx文件并将其转换为EMF模型实例文件(.xmi)。问题是典型的资源节约不起作用。我想将文件(创建运行时)保存在与输入文件相同的目录中。

下面的java类是我的命令处理程序类。在 Product p = Docx2ReqModelConverter.Convert(document); 行,我使用导入的项目类来解析文档并进行转换。它给了我生态模型的根元素对象。

我只想创建一个xmi文件并将其保存在运行时eclipse中。

public class ConvertHandler extends AbstractHandler implements IHandler {

@Override
public Object execute(ExecutionEvent event) {
    // TODO Auto-generated method stub

    XWPFDocument document = null;
    // Shell shell = HandlerUtil.getActiveShell(event);
    ISelection sel = HandlerUtil.getActiveMenuSelection(event);
    IStructuredSelection selection = (IStructuredSelection) sel;


    Object firstElement = selection.getFirstElement();

    if(firstElement instanceof IFile){

        IFile ifile = (IFile) Platform.getAdapterManager().getAdapter(firstElement, IFile.class);

        if (ifile == null) {
            if (firstElement instanceof IAdaptable) {
                ifile = (IFile) ((IAdaptable) firstElement).getAdapter(IFile.class);
            }
        }

        if (ifile != null) {

            File f = ifile.getLocation().toFile();
            try {


                document = new XWPFDocument(new FileInputStream(f));                    

                Product p = Docx2ReqModelConverter.Convert(document);
                createXMIFile(p);

                //Product p = Docx2ReqModelConverter.Convert(f);

            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


        }


    }
    return null;

}

/**
 * Saves the model instance and writes it to xmi file
 * 
 * @param product
 */
private static Resource createXMIFile(Product product) {

    ResourceSet resourceSet = new ResourceSetImpl();

    // Register XML Factory implementation using xmi extension
    resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(
            "xmi", new  XMLResourceFactoryImpl());


    // Create empty resource with the given URI
    Resource resource = resourceSet.createResource(URI.createURI("Testing/ReqModel.xmi"));


    // Add Product to contents list of the resource 

    resource.getContents().add(product);

    try{

        // Save the resource    
        resource.save(null);


    }catch (IOException e) {

        e.printStackTrace();
    }

    return resource;
}

}

非常感谢任何意见和建议。

0 个答案:

没有答案