3

This code does returns null InputStream as well as null URL. Why is that? I have my own class that I want to get the actual .class file as an InputStream to serialize to bytes[].

Class clazz = String.class;

String className = clazz.getName(); System.out.println(className);
URL url = clazz.getResource(className);
if( url != null )
{
  String pathName = url.getPath(); System.out.println(className);
}

InputStream inputStream = clazz.getResourceAsStream(className);
if(inputStream != null )
{
  System.out.println(inputStream.available());
}
sivabudh
  • 31,807
  • 63
  • 162
  • 228

2 Answers2

3

Firstly, you need the context's classloader. Secondly, you need to replace the dots . in classname by forward slashes / and suffix the .class extension to identify the real path.

So this one should work:

String name = String.class.getName().replace(".", "/") + ".class";
URL url = Thread.currentThread().getContextClassLoader().getResource(name);
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(name);

Edit: I should have added, inputStream.available() is not the way to learn about the file size. It just returns the amount of bytes which are available to read without blocking. With other words, the return value should never be treated as consistent. If you want to get the actual length, you'll really need to read the entire stream.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Copied, pasted, tested --> works! Three words: You are awesome. Thanks! – sivabudh Nov 23 '09 at 01:58
  • Oh thank you for telling me about the available() too! I thought available() was the size of the .class file. Thanks again for your details! – sivabudh Nov 23 '09 at 02:05
  • 2
    +1, though a simpler way (which I meant to write in the other question but messed up) is to use `clazz.getResourceAsStream(clazz.getSimpleName() + ".class")`. – ChssPly76 Nov 23 '09 at 03:17
0

First off, I'm not sure if you can get the actual .class file as a resource.

Secondly getName() will include the package and calling Class.getResource() will assume the path is relative to the class if it does not start with a slash.

You need to replace the '.'s in the class name with slashes and prepend a slash for getResource() to work correctly.

If you can get .class files as a resource you'd also need to append '.class' to the class name when calling getResource()

Community
  • 1
  • 1
leebutts
  • 4,882
  • 1
  • 23
  • 25