如何获取InputStream的内容?Eclipse项目.class文件流读取问题
读取Eclipse项目中.class文件InputStream内容的解决方案
嘿,我来帮你搞定这个问题!你现在是在Eclipse插件开发里遍历项目的.class文件,拿到了InputStream但不知道怎么读取内容对吧?下面给你两种实用的解决方法,结合你的代码来调整:
方法一:标准Java IO读取(适配二进制.class文件)
因为.class本质是二进制文件,直接读取字节内容会更靠谱,用ByteArrayOutputStream把流转换成字节数组或者字符串(如果是要转文本的话)。而且记得用try-with-resources自动关闭流,避免资源泄漏:
public void setFileList(IContainer container) throws CoreException, IOException { IResource[] members = container.members(); for (IResource member : members) { if (member instanceof IContainer) { setFileList((IContainer) member); } else if (member instanceof IFile && member.isDerived()) { IFile file = (IFile) member; // 用try-with-resources自动管理InputStream try (InputStream inputStream = file.getContents()) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int readLength; // 逐块读取流内容 while ((readLength = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, readLength); } // 如果需要二进制字节数组(解析.class文件常用) byte[] classFileBytes = outputStream.toByteArray(); // 这里可以添加对class字节的处理逻辑,比如用ASM解析 // 如果非要转成字符串(注意.class是二进制,转文本可能乱码) String contentStr = outputStream.toString(StandardCharsets.UTF_8); System.out.println("文件内容:" + contentStr); } catch (IOException e) { e.printStackTrace(); } } } }
方法二:用Eclipse自带的编码适配(适合文本类文件)
如果是处理文本文件(虽然你这里是.class,但可以参考),Eclipse的IFile能获取项目配置的字符集,用这个来读取会更适配项目编码:
public void setFileList(IContainer container) throws CoreException, IOException { IResource[] members = container.members(); for (IResource member : members) { if (member instanceof IContainer) { setFileList((IContainer) member); } else if (member instanceof IFile && member.isDerived()) { IFile file = (IFile) member; try (InputStream inputStream = file.getContents(); // 用Eclipse获取的文件字符集创建Reader BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, file.getCharset()))) { String line; // 逐行读取文本内容 while ((line = reader.readLine()) != null) { System.out.println("行内容:" + line); } } catch (IOException | CoreException e) { e.printStackTrace(); } } } }
小提醒
.class是二进制文件,用字符流读取大概率会出现乱码,所以优先用方法一的字节数组方式处理。- 如果要解析.class文件的结构(比如类名、方法),可以用ASM、Javassist这类字节码操作库,直接基于读取到的
byte[]来操作就行。
内容的提问来源于stack exchange,提问作者user8511720
相关产品推荐
相关产品推荐

