Java Reflection - Class.getResourceAsStream() Examples

Code Snippets Java Reflection Java 


Class:

java.lang.Class

java.lang.Objectjava.lang.Objectjava.lang.Classjava.lang.Classjava.io.SerializableSerializablejava.lang.reflect.GenericDeclarationGenericDeclarationjava.lang.reflect.TypeTypejava.lang.reflect.AnnotatedElementAnnotatedElementLogicBig

Method:

public InputStream getResourceAsStream(String name)
Parameters:
name - name of the desired resource
Returns:
A InputStream object or null if no resource with this name is found

See Also: Different ways to load classpath resources in Java

Examples


package com.logicbig.example.clazz;

import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

public class GetResourceAsStreamExample {

public static void main(String... args) throws IOException {
Class<GetResourceAsStreamExample> c = GetResourceAsStreamExample.class;
//getting this class
String resource = "/com/logicbig/example/clazz/GetResourceAsStreamExample.class";
InputStream rs = c.getResourceAsStream(resource);
String s = convertStreamToString(rs);
System.out.println(s);
}

private static String convertStreamToString(InputStream is) {
Scanner s = new Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}

Output

Êþº¾   4 R
 . / 0
1 2
 3 4 5
6 7 8
 9 :
 ;
 <
 = > ? <init> ()V Code LineNumberTable LocalVariableTable this 7Lcom/logicbig/example/clazz/GetResourceAsStreamExample; main ([Ljava/lang/String;)V args [Ljava/lang/String; c Ljava/lang/Class; resource Ljava/lang/String; rs Ljava/io/InputStream; s LocalVariableTypeTable JLjava/lang/Class<Lcom/logicbig/example/clazz/GetResourceAsStreamExample;>;
Exceptions @ convertStreamToString )(Ljava/io/InputStream;)Ljava/lang/String; is Ljava/util/Scanner;
StackMapTable A
SourceFile GetResourceAsStreamExample.java   5com/logicbig/example/clazz/GetResourceAsStreamExample </com/logicbig/example/clazz/GetResourceAsStreamExample.class B C D & ' E F G H I J java/util/Scanner  K \A L M N O P Q  java/lang/Object java/io/IOException java/lang/String java/lang/Class getResourceAsStream )(Ljava/lang/String;)Ljava/io/InputStream; java/lang/System out Ljava/io/PrintStream; java/io/PrintStream println (Ljava/lang/String;)V (Ljava/io/InputStream;)V useDelimiter '(Ljava/lang/String;)Ljava/util/Scanner; hasNext ()Z next ()Ljava/lang/String; !         /   *· ±          ‰     “   LM+,¶ N-¸ :² ¶ ±                4                   !   "     #  $   %
& '   i   » Y*· 
¶ L+¶ ™

§ °  
        (   ! )  * ü  A +  ,  -




See Also