保存EMF模型

时间:2014-09-16 09:10:58

标签: java emf

我是EMF的新手并尝试将EMF模型保存为以下: -

public void saveData(File file, Device device) throws IOException {  

        final ResourceSet resourceSet = new ResourceSetImpl();

        // Use XMI resource
        System.out.println("file path in  saveData " +file.getPath());          
        Resource xmiResource = resourceSet.createResource(URI.createFileURI(file.getPath() + ".xmi"));
        xmiResource.getContents().add(device);
        xmiResource.save(null);

        // Use XML resource instead
        Resource xmlResource = resourceSet.createResource(URI.createFileURI(file.getPath() + ".xml"));
        xmlResource.getContents().add(device);
        xmlResource.save(null);

        }

但是在指定的路径中没有创建文件。加载代码是: -

public Device loadData(String fileName) {


        final ResourceSet resourceSet = new ResourceSetImpl();


            // Use XMI resource

            Resource xmiResource;
            System.out.println("filename" + fileName);
            try {
            xmiResource = resourceSet.getResource(URI.createFileURI(fileName + ".xmi"),true);

                xmiResource.load(null);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }
            return (Device)xmiResource.getContents().get(0);

        }

,它给出以下错误: java.lang.RuntimeException:无法为'文件创建资源:/ C:/Users/Desktop/filename.xmi' ;;需要注册资源工厂

1 个答案:

答案 0 :(得分:7)

使用过XMiResourceImpl.It正常工作。

XMIResourceImpl resource = new XMIResourceImpl();
 File source = new File(fileName);
 resource.load( new FileInputStream(source), new HashMap<Object,Object>());
 Data data = (Data)resource.getContents().get(0);

用于保存模型

Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
Map<String, Object> m = reg.getExtensionToFactoryMap();
m.put("key", new XMIResourceFactoryImpl());
ResourceSet resSet = new ResourceSetImpl();
Resource resource = resSet.createResource(URI.createFileURI(fileName));
resource.getContents().add(data);
resource.save(Collections.EMPTY_MAP);