使用ResourceSet无法获取Workspace目录下的Autosar资源问题求助
解决AutosarResourceSet加载Workspace内文件的异常问题
我之前做Autosar工具链开发时也碰到过一模一样的问题!核心原因是Eclipse/Autosar的资源管理系统对Workspace内文件的处理逻辑和外部文件完全不同,你直接用URI.createFileURI()加载Workspace内的文件,相当于绕开了Eclipse的Workspace资源跟踪机制,自然会触发冲突或解析异常。
问题根源拆解
Workspace目录下的文件是被Eclipse的ResourcesPlugin统一管理的,包含锁机制、资源状态跟踪、路径映射等逻辑。当你用普通的file:// URI加载时,AutosarResourceSetImpl(基于EMF实现)会尝试直接访问文件系统,但此时该文件可能已经被Workspace的资源管理器锁定,或者路径解析时和Workspace的内部映射冲突,导致异常。
另外,你代码里的resourceSet.resources.add(resource)是多余的——getResource(uri, true)方法在成功加载资源后,会自动把资源加入到当前ResourceSet的资源列表中,重复添加反而可能引发资源重复注册的异常。
解决方案:区分Workspace内/外文件,使用对应URI格式
我们需要先判断目标文件是否在Workspace范围内,然后分别用平台URI(Workspace内)或普通file URI(外部)来加载:
// 1. 获取Workspace根目录的路径 IWorkspace workspace = ResourcesPlugin.getWorkspace(); IPath workspaceRootPath = workspace.getRoot().getLocation(); File targetFile = new File(inputfilepath); IPath targetFilePath = new Path(targetFile.getAbsolutePath()); URI resourceUri; // 2. 判断文件是否在Workspace内 if (workspaceRootPath.isPrefixOf(targetFilePath)) { // 转换为Eclipse平台资源URI(platform:/resource/...) IFile workspaceFile = workspace.getRoot().getFileForLocation(targetFilePath); if (workspaceFile != null && workspaceFile.exists()) { // 使用平台URI加载,让AutosarResourceSet通过Workspace资源系统访问 resourceUri = URI.createPlatformResourceURI(workspaceFile.getFullPath().toString(), true); } else { // fallback到普通file URI(防止特殊情况) resourceUri = URI.createFileURI(inputfilepath); } } else { // 外部文件,保持原有的file URI加载方式 resourceUri = URI.createFileURI(inputfilepath); } // 3. 加载资源(注意不需要手动add到resourceSet) val resourceSet = new AutosarResourceSetImpl(); Resource resource = resourceSet.getResource(resourceUri, true);
额外注意事项
- 如果还是出现异常,可以检查Workspace内的文件是否被其他进程或ResourceSet锁定,尝试关闭其他占用该文件的工具;
- 确保你的项目已经在Eclipse Workspace中正确导入,而非仅仅把文件放在Workspace目录下(Workspace目录下的未导入文件也不会被
ResourcesPlugin管理)。
内容的提问来源于stack exchange,提问作者goodman
相关产品推荐
相关产品推荐

