我的目的是在视图中显示其方法使用注解进行注释的(项目)所有文件。
我成功获得了项目的所有文件名,但无法将资源转换为对象以测试其是否带有注释。
我有一个java.io.StreamCorruptedException: invalid stream header: 7061636B
指向行ois = new ObjectInputStream(is);
,我自己也无法解释。仅供参考,我已经尝试使用FileInputStream,但是得到了相同的结果。
这是我的代码:
private boolean filenameIsAnnotated(IResource member) {
// transform a IResource into an Object
InputStream is = null;
ObjectInputStream ois = null;
Object object = null;
try {
is = ((IFile) member).getContents();
File f = member.getLocation().toFile();
is = new FileInputStream(f);
ois = new ObjectInputStream(is);
object = ois.readObject();
if (is != null && ois != null) {
// verify that one of the method is annotated
for (Method m : object.getClass().getMethods()) {
System.out.println(" method " + m.getName());
if (m.isAnnotationPresent(SPECIFICANNOTATION))
return true;
}
}
} catch (IOException | ClassNotFoundException | CoreException e) {
e.printStackTrace();
} finally {
if (is != null && ois != null) {
try {
is.close();
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
以下是使用此方法的情况,以防万一:
/**
* Recursively, go thru all the hierarchy of folders to find one given folder
* and return all of its files. A Container can be a IFolder, IProject or
* IWorkspaceRoot
*/
private ArrayList<String> processContainer(IContainer container, String filesLocationFolder) {
IResource[] members = null;
try {
members = container.members();
} catch (CoreException e) {
e.printStackTrace();
}
for (IResource member : members) {
if (member instanceof IContainer) {
processContainer((IContainer) member, filesLocationFolder);
} else if (member instanceof IFile) {
if (container instanceof IFolder) {
if (member.getFileExtension().equals("java")) {
//test if the file is annotated
if (filenameIsAnnotated(member))
fileList.add(member.getLocation().toFile().getName());
}
}
}
}
return fileList;
}
和调用先例的方法:
private ArrayList<String> getFileList(String projectName, String filesLocationFolder) {
// gets the workspace root
IWorkspaceRoot currentRoot = ResourcesPlugin.getWorkspace().getRoot();
IProject project = currentRoot.getProject(projectName);
try {
currentRoot.refreshLocal(IResource.DEPTH_INFINITE, null);
project.refreshLocal(IResource.DEPTH_INFINITE, null);
} catch (CoreException e) {
e.printStackTrace();
}
// Find the annotated files, return a list
ArrayList<String> list = processContainer(project, filesLocationFolder);
return list;
}
感谢您的帮助, K