(1).
new FileInputStream(“a.txt”)
那么,这个a.txt就应该在工程的根目录下.
比如:test_files/wdag0437ir.zip
(2).
this.getClass().getClassLoader().getResourceAsStream(“a.txt”)
也该在bin目录下,或加载类的地方–包外
(3).
this.getClass().getResourceAsStream(“a.txt”)
也该在bin目录下,或加载类的地方–包内
(4).
this.getClass()究竟得到的是什么东西?
是一个Class类的对象,注意,并不是Student类的对象,但是Student也是一个类。
Class也是一个普通的类,也可以实例化。
为什么可以从这个类对象中得到资源字节流呢?
可以这样理解:从一本书的对象中,你可以得到这本书的名字,也可以得到这本书到底有多少页。
书和书之间是不同的。
一个类对象和一个类对象也是不同,并且这些类位置必然是不同的,
getResourceAsStream:其本质是,根据类所在的位置,去加载配置文件所在的位置,
至于在测试时如何使用,还是直接使用相对路径较为方便。
1. getClass().getResourceAsStream应用
import java.applet.Applet; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Properties; public class Prop11 extends Applet { Image im; Font f; String msg; public void paint(Graphics g) { g.setFont(f); if (im != null) g.drawImage(im, 50, 100, this); if (msg != null) g.drawString(msg, 50, 50); } public void init() { InputStream is = getClass().getResourceAsStream("prop11.list"); Properties p = new Properties(); try { p.load(is); f = Font.decode(p.getProperty("MyProg.font")); msg = p.getProperty("MyProg.message"); String name = p.getProperty("MyProg.image"); URL url = getClass().getResource(name); im = getImage(url); } catch (IOException e) { System.out.println("error loading props..."); } } } File: prop11.list MyProg.font.size=20 MyProg.font.type=italic-bold MyProg.font.name=Helvetica MyProg.message=Hello World
2.添加一个或多个项目到类路径
import java.util.Properties; /** * Try adding one or more item(s) to class path. */ public class SysPropSet { static Properties p = System.getProperties(); public static void main(String[] argv) { System.out.println("System Properties:"); System.out.println("java.class.path now = " + getClassPath()); p.setProperty("java.class.path", getClassPath() + ';' + "C:/jdk1.2/lib/tools.jar"); System.out.println("java.class.path now = " + getClassPath()); try { Class.forName("sun.tools.javap.JavaP"); } catch (Exception e) { System.err.println(e); return; } System.out.println("Got it!!"); } static String getClassPath() { return p.getProperty("java.class.path", null); } }
3.加载资源文件:绝对从类路径
import java.io.IOException; import java.net.URL; public class Main { public static void main(String[] args) throws IOException { // absolute from the classpath URL url = Main.class.getResource("/mypackage/foo.txt"); } }
4.负载资源文件:相对于类的位置
import java.io.IOException; import java.net.URL; public class Main { public static void main(String[] args) throws IOException { // relative to the class location URL url = Main.class.getResource("foo.txt"); } }
5. 相对文件加载类路径
import java.io.IOException; import java.net.URL; public class Main { public static void main(String[] args) throws IOException { // relative document URL url = Main.class.getResource("docs/bar.txt"); } }