现在的位置: 首页 > 综合 > 正文

Java中的路径及Resource

2014年03月02日 ⁄ 综合 ⁄ 共 1296字 ⁄ 字号 评论关闭
     一直对Java的路径感觉模糊,用起来稀里糊涂。所知道的就是,如果使用相对路径类似于"myfile.txt"或者"res/image1.gif"的话,是在根路径下进行搜索的。
    而根路径到底是什么?感觉上似乎是包含了入口点(例如main函数)的类所在的路径。所知仅限于此。
    今天碰到一个问题,我的程序A需要从它的某个子路径读取一个文件,而我所编写的TestCase在运行时“根路径”就是Test Project的路径,这样一来,怎么也不能保证读取到正确的文件(由于某些原因,这些文件是静态指定的,而不是运行时动态传入的)。

    在网上四处乱撞,两眼一抹黑。试着打包成jar,也没用(笨蛋,当然没用)。最后还是在亲爱的《Core Java Volume I》中找到了答案。摘抄原文如下:
    The resource mechanism gives you the same convenience for files that aren''t class files. Here are the necessary steps:
 Get the Class object of the class that has a resource, for example, AboutPanel.class.
 Call getResource(filename) to get the resource location as a URL.
    If the resource is an image or audio file, read it directly with the getImage or getAudioClip method.
 Otherwise, use the openStream method on the URL to read in the data in the file. (See Chapter 12 for more on streams.)
 The point is that the class loader remembers how to locate the class, and then it can search for the associated resource in the same location.
 For example, to make an icon with the image file about.gif, do the following:

    URL url = AboutPanel.class.getResource("about.gif");
    ImageIcon icon = new ImageIcon(url);
 That means "locate the about.gif file at the same place where you find AboutPanel.class."

 所以说基础一定要打好,决定还是从第一章开始老老实实啃Core Java吧。

抱歉!评论已关闭.